The best way to remove array element by value

Here's how it's done:

var arr = ["orange","red","black","white"];
var index = arr.indexOf("red");
if (index >= 0) {
  arr.splice( index, 1 );
}

This code will remove 1 occurency of "red" in your Array.


There is an underscore method for this, http://underscorejs.org/#without

arr = ["orange","red","black","white"];

arr = _.without(arr, "red");

Back when I was new to coding I could hardly tell what splice was doing, and even today it feels less readable.

But readability counts.

I would rather use the filter method like so:

arr = ["orange","red","black","white","red"]

arr = arr.filter(val => val !== "red");

console.log(arr) // ["orange","black","white"]

Note how all occurrences of "red" are removed from the array.

From there, you can easily work with more complex data such as array of objects.

arr = arr.filter(obj => obj.prop !== "red");