How to Remove a Specific Item From an Array in JavaScript
Nick Scialli
September 05, 2020
Let’s remove an item from an array in JavaScript using a couple different approaches.
First Aproach: The Array.filter Method
Our first approach uses the Array.filter
method. It assumes the item we’re looking for could potentially come up multiple times in our array, and therefore we would want to remove every instance of it.
Here, we have an array of numbers and we want to remove 4
from that array.
const numbers = [1, 7, 4, 8, 4, 9, 2, 5, 8, 4];
const filtered = numbers.filter((x) => x !== 4);
console.log(filtered);
// [1, 7, 8, 9, 2, 5, 8];
Here we can see we have removed every instance of the number 4
from our array. Importantly, we haven’t mutated the input array, but rather we have a new variable called filtered
that has our new array.
Second Approach: Find and Splice
Our next approach assumes the element we’re trying to remove only occurs once in our array. We will find the index of that item using the indexOf
array method and then we’ll use the splice
array method.
Note: spice
will actually mutate our input array!
const numbers = [1, 7, 4, 8];
const index = numbers.indexOf(4);
if (index > -1) {
numbers.splice(index, 1);
}
console.log(numbers);
// [1, 7, 8];
There are a couple important caveats to this approach:
- This will only remove the first instance from
4
from our array! - This mutates our input array (i.e., it changes the
numbers
array rather than making some sort of copy of it).
Conclusion
There are a couple ways to remove an item from an array in JavaScript: one that doesn’t mutate the input array and removes every instance of the item and another that does mutate the input array and only removes the first instance.
Nick Scialli is a senior UI engineer at Microsoft.