Quantcast
Channel: upshots » ActionScript 3
Viewing all articles
Browse latest Browse all 10

JavaScript – remove multiple elements from an array

$
0
0

While you can always .filter() an array to remove unwanted elements, here’s a little sugar to remove all elements that evaluate truthily when compared to any argument passed:

Array.prototype.remove = function(){
    var args = Array.apply(null, arguments);
    var indices = [];
    for(var i = 0; i < args.length; i++){
        var arg = args[i];
        var index = this.indexOf(arg);
        while(index > -1){
            indices.push(index);
            index = this.indexOf(arg, index + 1);
        }
    }
    indices.sort();
    for(var i = 0; i < indices.length; i++){
        var index = indices[i] - i;
        this.splice(index, 1);
    }    
}

Usage:

var arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog"];
arr.remove("cat", "dog");
console.log(arr);  // => ["bear", "bird"] 

POC: http://jsfiddle.net/moagrius/yssfv/

Non-polluting:

function removeElements(array /*, ...args */){
    var args = Array.apply(null, arguments).slice(1);
    var indices = [];
    for(var i = 0; i < args.length; i++){
        var arg = args[i];
        var index = array.indexOf(arg);
        while(index > -1){
            indices.push(index);
            index = array.indexOf(arg, index + 1);
        }
    }
    indices.sort();
    for(var i = 0; i < indices.length; i++){
        var index = indices[i] - i;
        array.splice(index, 1);
    }    
}

Viewing all articles
Browse latest Browse all 10

Trending Articles