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?
5 Answers 5
> 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"]
Comments
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.
Comments
Count backwards:
// RIGHT
for (i = (remove.length-1); i >= 0; i--) {
arr.splice(remove[i]);
}
2 Comments
i = remove.length - 1length-1. And yes, I assumed a sort had taken place based on user's post, but it's a fair point.start the loop from last and remove the elements from highest index first.
Comments
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.
arrarray. (That or sort in ascending order, then loop in reverse order).