1

I have a set of keys (for example 2,3,4,101,102,454).

I'd like to remove elements with these keys from an array. Is there a way to remove them all at once?

I tried iterating through for loop, and using splice to remove elements one by one, but that never removed all elements - my guess is because it modifies the array I'm looping through.

1
  • pls put your code to help better. Commented Jan 17, 2012 at 15:30

2 Answers 2

10

go backwards.

If you loop thru from 0 -> n, you modify the indexes of the elements coming after an item you just removed.

If you go backwards, from n -> 0, you don't have that problem.

Sign up to request clarification or add additional context in comments.

Comments

1

You can sort your indexes to remove largest first-

//array=array, removal=[2,3,4,101,102,454]

var i=0, L=removal.length;
removal.sort(function(a,b){return b-a});
while(i< L){
    array.splice(removal[i],1);
}

Comments

Your Answer

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.