Search code examples
javascriptarraysindices

Remove an array of indices from a JavaScript array


I have an array:

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

and I have an array of indices which I wish to remove:

var remove = [1, 3, 5]

so that the result is :

arr ==== ['A', 'C', 'E', 'G']

I can't do it with splice in a loop:

// WRONG
for (i = 0, l = remove.length; i < l; i++) {
    arr.splice(remove[i]);
}

because after every iteration the index of each element has changed.

So how can I do this?


Solution

  • > arr.filter(function(x,i){return remove.indexOf(i)==-1})
    ["A", "C", "E", "G"]
    

    To be more efficient, convert remove into an object/hashtable first, like so:

    var removeTable = {}
    remove.forEach(function(x){removeTable[x]=true})
    
    > arr.filter(function(x,i){return removeTable[i]})
    ["A", "C", "E", "G"]