简体   繁体   English

javascript基于另一个具有相同对象和值的数组从数组中删除

[英]javascript delete from array based on another array with same object and values

I have an array of objects (all the same object type). 我有一个对象数组(所有相同的对象类型)。 I have another array of the same object type in which I want to use to tell me which objects to delete from the first array. 我有另一个相同对象类型的数组,我想用它来告诉我从第一个数组中删除哪些对象。 Is there an easy way to do this besides looping through all properties and comparing them to find the elements in the first array that 100% match the elements in the second array and then deleting from the first array? 除了循环遍历所有属性并比较它们以找到第一个数组中与第二个数组中的元素100%匹配然后从第一个数组中删除的元素之外,还有一种简单的方法吗?

I'm basically doing a jQuery.grep() on an array of objects and the resulting array from this grep I want to delete from the array I passed into it. 我基本上在一个对象数组上做一个jQuery.grep(),从这个grep得到的数组我想从我传入它的数组中删除。

Instead of using jQuery.grep(), to obtain a new array, replace it with jQuery.map() , returning the same object if it must be kept, or null if you want to remove it. 不使用jQuery.grep()来获取新数组,而是将其替换为jQuery.map() ,如果必须保留则返回相同的对象,如果要删除它则返回null。

If for instance your code is 例如,如果您的代码是

var toBeDeleted = $.grep(array, function(val) {
  return condition(val);
});

Change it to 将其更改为

array = $.map( array, function(val) {
  if(condition(val))
    return null;
  return val;
});

If all it is is an array of values that need to be deleted from another array then looping through the arrays is really quite easy. 如果它只是一个需要从另一个数组中删除的值数组,那么循环遍历数组真的很容易。

function deleteMatchingValues( target, toBeDeleted, oneMatch ) {
    var i = target.length, j = toBeDeleted.length;

    while( i-- ) {
        while( j--) {
            if( target[i] === toBeDeleted[j] ) {
                target.splice(i,1);
                if( oneMatch ) { break; }
            }
        }
        j = toBeDeleted.length;
    }
}

The above function includes a parameter for when you know there is only single instances of the value in the array. 上面的函数包含一个参数,用于知道数组中只有单个值的实例。

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

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