fod
fod

Reputation: 258

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?

Upvotes: 1

Views: 132

Answers (5)

Nick
Nick

Reputation: 6025

As an alternative suggestion, you could use .push() to send the items you want to keep to a third array. See here for the basics. This would allow you to keep the original array intact, although it seems you don't want/need to do this.

Upvotes: 0

DanRedux
DanRedux

Reputation: 9359

To not change your thinking too much- Start at the end.

A B C D E F..

When you remove element 5, it becomes..

A B C D E

Then you remove element 3, it becomes..

A B C E

Which is exactly what you want.

Upvotes: 2

Vivek Viswanathan
Vivek Viswanathan

Reputation: 1963

start the loop from last and remove the elements from highest index first.

Upvotes: 1

Marc
Marc

Reputation: 11633

Count backwards:

// RIGHT
for (i = (remove.length-1); i >= 0; i--) {
  arr.splice(remove[i]);
}

Upvotes: 1

ninjagecko
ninjagecko

Reputation: 91159

> 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"]

Upvotes: 2

Related Questions