简体   繁体   English

JS / Jquery-通过键从数组中删除多个元素

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

I have a set of keys (for example 2,3,4,101,102,454). 我有一组键(例如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. 我尝试遍历for循环,并使用splice地删除元素,但那从未删除所有元素-我的猜测是因为它修改了我正在遍历的数组。

go backwards. 倒退。

If you loop thru from 0 -> n, you modify the indexes of the elements coming after an item you just removed. 如果从0-> n循环,则修改刚删除的项之后的元素的索引。

If you go backwards, from n -> 0, you don't have that problem. 如果从n-> 0向后退,则不会出现此问题。

You can sort your indexes to remove largest first- 您可以对索引进行排序,以删除最大的

//array=array, removal=[2,3,4,101,102,454] // array = array,删除= [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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM