const input = [1,2,3,4,5,6,8,5]; const removeNumber = 5; const result = input.filter( item => item != removeNumber );
Above example uses array.prototype.filter function. It iterates over all array items, and returns only those satisfying arrow function. As a result, old array stays intact, while a new array called result contains all items that are not equal to five.
You can test it yourself online: jsfiddle
You can visualize how array.prototype.filter like this:
Array.filter.prototype is far the most readable method to remove a number in this case. It leaves little place for mistakes and uses core JS functionality.
Why not array.prototype.map?
Array.prototype.map is sometimes consider as an alternative for array.prototype.filter for that use case. But it should not be used. The reason is that array.prototype.filter is conceptually used to filter items that satisfy arrow function (exactly what we need), while array.prototype.map is used to transform items. Since we don't change items while iterating over them, the proper function to use is array.prototype.filter.
As of today (2.12.2020) 97,05% of Internet users browsers support array.prototype.filter. So generally speaking it is safe to use. However, IE6 - 8 does not support it. So if your use case requires support for these browsers there is a nice polyfill made by Chris Ferdinanti.
Top comments (0)