比较两个带有对象的数组,并创建带有不匹配对象的新数组 [英] Compare two Arrays with Objects and create new array with unmatched objects

查看:83
本文介绍了比较两个带有对象的数组,并创建带有不匹配对象的新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个Javascript数组:

I have the following two Javascript arrays:

const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];

我现在想要一个新数组array3,该数组仅包含array2中尚未存在的对象,所以:

I now want a new array array3 that contains only the objects that aren't already in array2, so:

const array3 = [{ id: 2}, { id: 4 }];

我尝试了以下操作,但是它返回了所有对象,并且当我将条件更改为===时,它返回了array2的对象.

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});

有什么主意吗?欢迎使用ES6

Any idea? ES6 welcome

推荐答案

您可以反转比较(等于而不是不等于),并返回some的求反结果.

You could reverse the comparison (equal instead of unqual) and return the negated result of some.

const
    array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
    array2 = [{ id: 1 }, { id: 3 }],
    array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id));
    //                               ^                                ^^^

console.log(array3);

这篇关于比较两个带有对象的数组,并创建带有不匹配对象的新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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