Last Updated: February 25, 2016
·
4.673K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside