How to remove a number from an array with JavaScript? Let me show how to do it:
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.
Online demo
You can test it yourself online: jsfiddle
You can visualize how array.prototype.filter like this:
Considerations
Code quality
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.
Support
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.
Performance
Array.prototype.filter is great for most use cases. However if you are looking for some performance improvements for advanced data processing you can explore some other options like using pure for. Another great option is to rethink if really array you are processing has to be so big, it may be a sign that JavaScript should receive reduced array for processing from the data source.
Top comments (0)