How to remove item from array by value?
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:
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()
:
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.
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:
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:
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:
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:
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:
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:
Moreover, when you need to preserve the primal array, filter()
retains its sworn promise by returning a fresh array and leaving the original unscathed:
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.
Was this article helpful?