我有两个对象数组。
Size attribute
0 2 V2
1 3 V3
2 1 V1
3 4 V3
我想比较这些对象,我的最终结果将是
e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]
我尝试过
result = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11}]
但是得到了
let result = e.filter(o1 => f.some(o2 => o1.qId != o2.qId));
如何实现所需的输出?
答案 0 :(得分:2)
您似乎应该过滤f
,而不是e
,因为result
显示的是f
而不是e
的值。
为了使复杂度最小,请将e
数组的qId
转换为Set
,以便首先进行快速查找。 (与Set
的{{1}}复杂度相比,{O(1)
s具有O(N)
的查找时间)
.some
答案 1 :(得分:2)
我希望您需要比较qId。
let e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
let f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]
let res = [];
f.forEach(fo => {
e.forEach(eo => {
if(fo.qId === eo.qId){
res.push(fo)
}
})
})
console.log(res)
答案 2 :(得分:1)
您可以结合使用Array.filter()
和Array.some()
来获得结果:
e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}];
var res = f.filter(fItem => e.some(({qId}) => fItem.qId === qId));
console.log(res);
答案 3 :(得分:0)
您可以检查数组e
是否具有相同的qId
值来过滤f
。
var e = [{ uniqueId: '', active: 'a', qId: 10 }, { uniqueId: '', active: 'a', qId: 11 }],
f = [{ uniqueId: 50, active: 'a', qId: 10 }, { uniqueId: 51, active: 'a', qId: 11 }, { uniqueId: 52, active: 'a', qId: 13 }],
result = f.filter(({ qId }) => e.some(o => o.qId === qId));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }