Remove value from array
suggest changeWhen you need to remove a specific value from an array, you can use the following one-liner to create a copy array without the given value:
array.filter(function(val) { return val !== to_remove; });
Or if you want to change the array itself without creating a copy (for example if you write a function that receives an array and mutates it) you can use this snippet. The assignment must be inside the comparison. !== binds tighter than =, so an unparenthesized assignment stores true and splice deletes the wrong index:
let index;
while ((index = array.indexOf(to_remove)) !== -1) {
array.splice(index, 1);
}
And if you need to remove just the first value found, remove the while loop:
const index = array.indexOf(to_remove);
if (index !== -1) { array.splice(index , 1); }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents