简体   繁体   English

如何按值删除数组中的多个项目?

[英]How to delete multiple items of an array by value?

I am trying to make a removeAll() function, which will remove all elements of an array with that particular value (not index). 我试图创建一个removeAll()函数,它将删除具有该特定值(而不是索引)的数组的所有元素。

The tricky part comes when we make any change to the loop, the indexes tend to move around (making it very hard to make it work like we want) and, restarting the loop every time we make changes is very inefficient on big arrays. 当我们对循环进行任何更改时,棘手的部分就出现了,索引往往会移动(使得它很难使它像我们想要的那样工作),并且每次进行更改时重新启动循环在大数组上都是非常低效的。

So far, I wrote my own arr.indexOf function (for older IE support), it looks like this: 到目前为止,我编写了自己的arr.indexOf函数(对于较旧的IE支持),它看起来像这样:

function arrFind(val, arr) {
    for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
        if (arr[i] === val) {
            return i;
        }
    }
    return -1;
}

It is easy to remove elements like this: 删除这样的元素很容易:

var myarray = [0, 1, 2, 3, 4];
var tofind = 2;

var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
    myarray.splice(stored_index, 1);
}

alert(myarray.join(",")); //0,1,3,4

However, as I pointed out earlier, when doing this while looping, we get in trouble. 但是,正如我前面指出的那样,在循环时执行此操作时,我们遇到了麻烦。

Any ideas on how to properly remove array items while looping through it? 有关如何在循环中正确删除数组项的任何想法?

以相反顺序循环或使用不要删除的项构建新数组。

Every new browser has an Array filter method: 每个新浏览器都有一个Array过滤方法:

var myarray=[0,1,2,3,4];
var removal=2;
var newarray=myarray.filter(function(itm){return itm!==removal});

Try this one. 试试这个吧。 You just have to check the indices of the numbers you would like to remove. 您只需要检查要删除的数字的索引。 I have added additional elements in your array. 我在你的数组中添加了其他元素。

var myarray = [0, 1, 2, 3, 2, 2, 2, 5, 6];
var indicesToRemove = new Array();

for(i=0;i<myarray.length;i++){
    if(myarray[i]===2){ //let's say u wud like to remove all 2 
        indicesToRemove.push(i); //getting the indices and pushing it in a new array
    }
}

for (var j = indicesToRemove.length -1; j >= 0; j--){
    myarray.splice(indicesToRemove[j],1);
}

alert(JSON.stringify(myarray)); //myarray will be [0,1,3,5,6]

I wrote this little function where arr is the original array and d1, d2 the values you want removed. 我写了这个小函数,其中arr是原始数组,d1,d2是你想要删除的值。 I wonder how it could be generalized to an arbitrary number of values to be removed. 我想知道如何将其推广到要删除的任意数量的值。 Well, I'm just a beginner. 好吧,我只是个初学者。

function destroyer(arr, d1, d2) {
    var lean =[];
    for (var i = 0; i<arr.length; i++) {
        if (arr[i] != d1 && arr[i] != d2) {
            lean.push(arr[i]);
        }
    }
  return lean;

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

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