Last Updated: February 25, 2016
·
4.345K
· ffleandro

Javascript ArrayList

In many Javascript projects I've felt the need to use an ArrayList (like in Java or other languages). However the Javascript Array Object lacks a few convenience methods:

Array.prototype.remove = function(el){
    var index = this.indexOf(el);
    if(index != -1) {
        this.splice(index, 1);
    }
}

Array.prototype.add = function(el){
    if(this.indexOf(el) == -1){
        this.push(el);
    }
}

Array.prototype.contains = function(el){
    return this.indexOf(el) != -1;
}

Array.prototype.toggle = function(el){
    if(this.indexOf(el) == -1){
        this.add(el);
    } else this.remove(el);
}

Hope this is as useful for someone as it has been for me.