Last Updated: February 25, 2016
· euantor

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?

3 Responses
Add your response

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

To use it:

var myArray = ["element", "element1", "element2", "element1"];
over 1 year ago ·

@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 ·

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 ·