TypeOfNaN

How to Remove a Specific Item From an Array in JavaScript

Nick Scialli September 05, 2020🚀 1 minute read

If you're enjoying this blog, please consider one or both of the following:

unique item

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

Nick Scialli is a software engineer at the U.S. Digital Service.

Subscribe to the mailing list!

If you like what I post here, please sign up to get updates and code insights in your inbox. I won't spam you and you can unsubscribe any time!

Powered by Buttondown.