包含对象的两个数组的差异和交集 [英] Difference and intersection of two arrays containing objects
问题描述
我有两个数组 list1
和 list2
,它们有一些属性的对象;userId
是 Id 或唯一属性:
list1 = [{用户ID:1234,用户名:'XYZ'},{用户ID:1235,用户名:'ABC'},{用户ID:1236,用户名:'IJKL'},{用户ID:1237,用户名:'WXYZ'},{用户ID:1238,用户名:'LMNO'}]列表 2 = [{用户ID:1235,用户名:'ABC'},{用户ID:1236,用户名:'IJKL'},{ 用户 ID:1252,用户名:'AAAA' }]
我正在寻找一种简单的方法来执行以下三个操作:
<预><代码>[{用户ID:1235,用户名:'ABC'},{用户ID:1236,用户名:'IJKL'}]list1 操作 list2
应该返回元素的交集:
<预><代码>[{用户ID:1234,用户名:'XYZ'},{用户ID:1237,用户名:'WXYZ'},{用户ID:1238,用户名:'LMNO'}]list1 operation list2
应该返回list1
中没有出现在list2
中的所有元素的列表:
<预><代码>[{ 用户 ID:1252,用户名:'AAAA' }]list2 operation list1
应该返回list2
中没有出现在list1
中的元素列表:
这是对我有用的解决方案.
var intersect = function (arr1, arr2) {var intersect = [];_.each(arr1, 函数 (a) {_.each(arr2, 函数 (b) {如果(比较(a,b))intersect.push(a);});});返回相交;};var unintersect = function (arr1, arr2) {var unintersect = [];_.each(arr1, 函数 (a) {var 发现 = 假;_.each(arr2, 函数 (b) {如果(比较(a,b)){发现 = 真;}});如果(!找到){unintersect.push(a);}});返回不相交;};函数比较(a,b){如果(a.userId === b.userId)返回真;否则返回假;}
I have two arrays list1
and list2
which have objects with some properties; userId
is the Id or unique property:
list1 = [
{ userId: 1234, userName: 'XYZ' },
{ userId: 1235, userName: 'ABC' },
{ userId: 1236, userName: 'IJKL' },
{ userId: 1237, userName: 'WXYZ' },
{ userId: 1238, userName: 'LMNO' }
]
list2 = [
{ userId: 1235, userName: 'ABC' },
{ userId: 1236, userName: 'IJKL' },
{ userId: 1252, userName: 'AAAA' }
]
I'm looking for an easy way to execute the following three operations:
list1 operation list2
should return the intersection of elements:[ { userId: 1235, userName: 'ABC' }, { userId: 1236, userName: 'IJKL' } ]
list1 operation list2
should return the list of all elements fromlist1
which don't occur inlist2
:[ { userId: 1234, userName: 'XYZ' }, { userId: 1237, userName: 'WXYZ' }, { userId: 1238, userName: 'LMNO' } ]
list2 operation list1
should return the list of elements fromlist2
which don't occur inlist1
:[ { userId: 1252, userName: 'AAAA' } ]
This is the solution that worked for me.
var intersect = function (arr1, arr2) {
var intersect = [];
_.each(arr1, function (a) {
_.each(arr2, function (b) {
if (compare(a, b))
intersect.push(a);
});
});
return intersect;
};
var unintersect = function (arr1, arr2) {
var unintersect = [];
_.each(arr1, function (a) {
var found = false;
_.each(arr2, function (b) {
if (compare(a, b)) {
found = true;
}
});
if (!found) {
unintersect.push(a);
}
});
return unintersect;
};
function compare(a, b) {
if (a.userId === b.userId)
return true;
else return false;
}
这篇关于包含对象的两个数组的差异和交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!