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.


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");

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

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

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

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

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

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]


Array.prototype.deleteElem = function(val) {
    var index = this.indexOf(val); 
    if (index >= 0) this.splice(index, 1);
    return this;
}; 
var arr = ["orange","red","black","white"];
var arr2 = arr.deleteElem("red");