如果对象包含在另一个数组中,则从数组中删除它 [英] Remove object from array if it is contained in another array

查看:90
本文介绍了如果对象包含在另一个数组中,则从数组中删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从数组中删除一个对象,如果该对象的属性(唯一)包含在另一个数组中。我知道我可以这样做一个嵌套的for循环:

I am trying to remove an object from an array, if that object's property (unique) is included in the other array. I know I can do a nested for-loop like this:

for(i = 0; i < array.length; i++) {
    for(j = 0; j < array2.length; j++) {
        if(array[i].Email === array2[j].Email) {
            //remove array[i] object from the array
        }
    }
}

或者其他什么。这样的事情。那有ES6过滤器吗?我可以轻松地对带有字符串的常规数组进行过滤,但是使用对象数组进行过滤会有点棘手。

Or whatever. Something like that. Is there an ES6 filter for that? I can easily do a filter up against a regular array with strings, but doing it with an array of objects is a bit more tricky.

推荐答案

不是最优,但试试这个

array = array.filter( function( item ){
  return array2.filter( function( item2 ){
    return item.Email == item2.Email;
  }).length == 0;
});

尝试查找,它赢了迭代所有元素并在第一次匹配后中断

Try with find as well, it won't iterate all the elements and will break after first match itself

array = array.filter( function( item ){
  return array2.find( function( item2 ){
    return item.Email == item2.Email;
  }) == undefined;
});

这篇关于如果对象包含在另一个数组中,则从数组中删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆