Explain Codes LogoExplain Codes Logo

How to remove item from array by value?

javascript
array-manipulation
javascript-prototype
filter-method
Nikita BarsukovbyNikita Barsukov·Sep 30, 2024
TLDR

Get rid of a specific value in your array in a quick and effective way by putting to good use the Array.prototype.filter() method. Here is a short demonstration:

let arr = [1, 2, 3]; arr = arr.filter(v => v !== 2); // arr is now [1, 3], the '2' got bored and left!

Modifying original array

Rather than creating a new array, you may want to modify the existing one. You can realize that with the Array.prototype.splice() coupled with the Array.prototype.indexOf():

let arr = [1, 2, 3]; const index = arr.indexOf(2); // Let's find where '2' is hiding. if (index !== -1) { arr.splice(index, 1); // Gotcha '2'! You're out. } // arr is now [1, 3]

But mind this: this method will oust the first occurrence of the value only.

Dealing with multiples and compatibility

Discarding multiple values

If your array has multiple instances of a particular value that you'd like to banish, filter() is your loyal servant.

let arr = [1, 2, 2, 3]; arr = arr.filter(v => v !== 2); // All '2's are sent to exile.

Yet, if the array's integrity is of essence and you must eliminate multiple values, a do...while loop with a dash of splice() can do the trick:

let arr = [1, 2, 2, 3]; let index; do { index = arr.indexOf(2); if (index !== -1) { arr.splice(index, 1); // '2's are being caught and kicked out one by one. Sergi Roberto style. } } while (index !== -1); // arr is now [1, 3]

Bearing browser compatibility in mind

Sure, filter() is well-known and quite popular but remember that the ES6 party isn't attended by the likes of IE11 where arrow function syntax (=>) is persona non grata. In such scenarios, function expressions are the way to go:

arr = arr.filter(function(v) { return v !== 2; });

Also consider that indexOf() isn't on speaking terms with IE8 and anything older. Here, either polyfill comes to the rescue or you could rewrite the code as follows:

for (var i = arr.length - 1; i >= 0; i--) { if (arr[i] === 2) { arr.splice(i, 1); // '2', you know you can't hide. You're history. } }

Enhancing with sugar, spice, and everything nice

Expanding the array prototype

To facilitate your coding journey, you can grow the Array prototype with custom methods:

Array.prototype.removeValue = function(value) { this.splice(this.indexOf(value), 1); }; arr.removeValue(2); // The array cuts the '2' loose by itself!

Heads up: Tweaking the Array prototype may yield baffling results with identical prototype manipulations, especially in grandiose codebases or external libraries.

Jazzing it up with libraries

Sometimes less is more. A utility library like underscore.js works wonders for sprucing up your codebase:

arr = _.without(arr, 2);

Just like that, _.without() whisks away all instances of 2 and doesn't even flinch at the originally unmoved array.

Niche removal strategies

At times you might encounter arrays with objects or complex data types, and want to remove an item relying on a property value . Here filter() becomes your knight in shining armor:

let people = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }]; people = people.filter(person => person.name !== 'Bob'); // Sorry Bob, you have been voted off the island, people is now [{ name: 'Alice' }, { name: 'Charlie' }]

Moreover, when you need to preserve the primal array, filter() retains its sworn promise by returning a fresh array and leaving the original unscathed:

const originalArray = [1, 2, 3, 4]; const newArray = originalArray.filter(v => v !== 3); // originalArray doesn't budge an inch!

Following the difference between editing the substance and yielding a new array is critical, especially when handling React state or similar circumstances where immutability matters.