Removing an item from an array is a common operation we do in JavaScript programs.
In this article, we’ll look at how to remove a specific element from a JavaScript array.
Splice
We can use the array’s splice
method to remove an array item with the given index.
For instance, we can write:
const array = [1, 2, 3];
console.log(array);
const index = array.indexOf(2);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
We have an array
that we want to remove an item from.
We use the indexOf
method to find the first index of the given item in the array.
If it returns anything other than -1, then the item is in the array.
And so if index
isn’t -1, we call splice
with the index
and 1 to remove an item with the given index.
This works well with one entry and if we’re looking for a primitive value.
Filter
We can also use the filter
method to return the array without the given entry.
For instance, we can write:
const value = 3
let arr = [1, 2, 3, 4, 5]
arr = arr.filter(item => item !== value)
console.log(arr)
We look for value
in arr
and remove it by calling filter
with a callback that returns item !== value
.
This will keep anything in arr
that has value other than value
.
This will remove all entries with the given value
so it’s more versatile than using indexOf
and splice
.
It also works with objects, which makes it more versatile.
indexOf
doesn’t work with objects since we can’t specify the condition to look with a callback as we do with filter
.
Conclusion
We can remove items with the given condition easily from JavaScript arrays.