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.
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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.