yfk_za
Last Updated: February 25, 2016
·
5.499K
· euantor
Irnhmv6

Array method to remove by value in JavaScript

Ever had an array in javaScript and felt the need to remove items with a specific value? Unfortunately there is no inbuilt method to accomplish this task. However, if you add the snipept below to the top of your JS file you can do just that!

Array.prototype.remove= function(){
    var what, a= arguments, L= a.length, ax;
    while(L && this.length){
        what= a[--L];
        while((ax= this.indexOf(what))!= -1){
            this.splice(ax, 1);
        }
    }
    return this;
}

To use it, see below:

var myArray = ["element", "element1", "element2", "element1"];
myArray = myArray.remove("element");

Pretty easy, eh?

Say Thanks
Respond

3 Responses
Add your response

532
8609ef19a20a567d201bcb4259808ab9
Array.prototype.remove = function (target) {
    this.splice(this.indexOf(target), 1);
    return this;
};

To use it:

var myArray = ["element", "element1", "element2", "element1"];
myArray.remove("element");
over 1 year ago ·
533
Irnhmv6

@nostalgia That is a good deal easier... My method allows you to remove multiple items IIRC though. I picked it up a while ago.

over 1 year ago ·
16128
2f66c42d644cabb3394caf024748fe98

Of you can use Underscore and a functional approach to do

var myArr = _.without(['element1', 'element2', 'element', 'element', 'element3'], 'element', 'element1');
console.log(myArr); // ['element2', 'element3']

You can even remove several elements.

over 1 year ago ·