How to remove a specific item from an array in JavaScript?
In this tutorial, we will learn the two most common ways to remove a specific element from an array in JavaScript.
Using splice
Method
The splice
method in JavaScript is used to add or remove elements from an array. To remove an item from an array using the splice
method, you need to know the index of the item you want to remove. Here’s how you can do it:
- Find the index of the item you want to remove.
- Use the
splice
method to remove the item at that index.
let numbers = [2, 4, 5, 6];
// Find the index of the item you want to remove
// Suppose we want to remove 5
let i = numbers.indexOf(5);
if (i !== -1) {
numbers.splice(i, 1); // here second parameter, aka 1 means remove one item only
}
console.log(numbers); // [2, 4, 6]
Using the splice
method is a straightforward way to remove item(s) from an array by specifying the starting index and the number of items to remove. By finding the index of the item you want to remove and then applying splice
, you can effectively manage array elements in JavaScript.
Using filter
Method
The filter
method in JavaScript creates a new array with all elements that pass the test implemented by the provided function. To remove a specific item from an array, you can use the filter
method to include only those elements that do not match the item you want to remove.
Suppose we have an array of numbers and we want to remove the number 3 from it:
let numbers = [1, 2, 3, 5];
let even = 2; // number to remove
// Use the filter method to remove the item
numbers = numbers.filter((num) => num !== even);
console.log(numbers); // [1, 3, 5]
Explanation:
- The
filter
method takes a callback function that is applied to each element of the array. If the callback function returnstrue
for an element, that element is included in the new array. If it returnsfalse
, the element is excluded. - In the example,
num => num !== even
is the condition. It returnstrue
for all items that are not equal to 2, so all elements except 2 are included in the new array.
Using the filter
method is an elegant way to remove items from an array by including only the elements that do not match the specified condition. This method is useful when you want to create a new array that excludes certain items based on a specific criterion.
So there you go, these simple methods can help you remove a specific item from an array in JavaScript.