CodeVirtuoso
CodeVirtuoso

Reputation: 6438

JS / Jquery - Remove multiple elements from an array by keys

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.

Upvotes: 1

Views: 2559

Answers (2)

kennebec
kennebec

Reputation: 104780

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);
}

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120198

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.

Upvotes: 10

Related Questions