1

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?

asked Apr 22, 2012 at 4:49
2
  • 1
    Start at the end of the array, and work backwards? Commented Apr 22, 2012 at 4:52
  • 1
    Sort your remove array so the keys are in descending order, so you work from the BACK of the arr array. (That or sort in ascending order, then loop in reverse order). Commented Apr 22, 2012 at 4:53

5 Answers 5

2
> 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"]
answered Apr 22, 2012 at 4:52
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Apr 22, 2012 at 4:53

Comments

1

Count backwards:

// RIGHT
for (i = (remove.length-1); i >= 0; i--) {
 arr.splice(remove[i]);
}
answered Apr 22, 2012 at 4:52

2 Comments

This assumes the remove array has no duplicates, and is sorted. If the remove array was sorted in reverse it would still have the same problem as before. Also, the init part of the for loop should be i = remove.length - 1
Updated for the length-1. And yes, I assumed a sort had taken place based on user's post, but it's a fair point.
1

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

answered Apr 22, 2012 at 4:52

Comments

0

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.

answered Apr 22, 2012 at 5:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.