The easiest way to remove a specific item from the JavaScript array is the splice
method.
General approach
First, start by locating the item you’d like to delete.
const arr = [1, 2, 3, 4, 5];
const itemToRemove = 2;
const indexOfTheItemToRemove = array.indexOf(itemToRemove);
Now you can use splice
to remove the element from the array.
arr.splice(indexOfTheItemToRemove, 1);
There are 2 possible corner cases, that you should handle carefully.
A missing item
First, the item you’re looking for may not be present in the array.
In this case indexOfTheItemToRemove
will equal -1
and there’s no reason
to splice the array.
We can rephrase that and say that it only makes sense to splice the array when
the indexOfTheItemToRemove
is greater than -1
if (indexOfTheItemToRemove > -1) {
arr.splice(indexOfTheItemToRemove, 1);
}
Multiple matching items
Second, the array may contain multiple items equal to the itemToRemove
.
If you want to delete only the first one, then you’re perfectly fine as the code
above will just delete the very first occurrence of the itemToRemove
.
But, if your goal is to remove all the matching elements from the array, then I suggest
using the filter
function.
const filteredArray = arr.filter(item => item !== itemToRemove);
Keep in mind that filter
returns a new array which we store in the filteredArray
constant.
The filter
function does not modify the original array.