Removing an item from a JavaScript array is something that we have to do often.
In this article, we’ll look at how to remove a specific item from a JavaScript array.
The indexOf and splice Methods
One way to remove an item from an array is to use the indexOf
method to get the index of the item we want to remove.
Then we can use the splice
method to remove an 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);
}
We have the array
array.
Then we call indexOf
to get the index of 2 in array
.
And then we call splice
with index
and 1 to remove 1 item starting with index index
.
This means we remove the item with index index
in array
with splice
if index
is bigger than -1.
indexOf
returns -1 if the item doesn’t exist in array
.
The filter Method
We can call filter
to return an array without the item we want to remove.
For instance, we can write:
let array = [1, 2, 3];
const value = 3
array = array.filter((item) => {
return item !== value
})
We have the array
which is the array, and value
which is the value want to remove from array
.
Then we call filter
with a callback to return item !== value
.
This means that we want the array returned by item
to not include the item with the value value
.
Therefore, array
should be [1, 2]
.
Removing Multiple Items
If we want to remove multiple items, we can also use the filter
method, but with a different callback.
To remove multiple items, we can write:
let array = [1, 2, 3];
const forDeletion = [2, 3]
const value = 3
array = array.filter((item) => {
return !forDeletion.includes(item)
})
console.log(array)
We call array.filter
with a callback that checks if the item isn’t in the forDeletion
array.
forDeletion
is an array with the items we want to delete.
So if it’s not included in forDeletion
, then we want to keep them.
Since 2 and 3 in in forDeletion
, that means only 1 is kept in the returned array.
Conclusion
The array instances’ includes
, indexOf
, splice
, and filter
methods are handy for removing items in an array.