[英]Comparing two array of object javascript and remove values that are not equal
I have two array of objects. 我有两个对象数组。
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}]
I want to compare these objects and my final result will be like 我想比较这些对象,我的最终结果将是
result = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11}]
I tried 我试过了
let result = e.filter(o1 => f.some(o2 => o1.qId != o2.qId));
But am getting 但是越来越
[{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]
How to achieve the desired output? 如何达到期望的输出?
It looks like you should be filtering f
, not e
, because the result
shows values from f
, not from e
. 看起来您应该过滤
f
而不是e
,因为result
显示的是f
而不是e
。
For the least complexity, turn the e
array's qId
s into a Set
for quick lookup first. 为了使复杂度最小,请首先将
e
数组的qId
转换为Set
以便快速查找。 ( Set
s have O(1)
lookup time, compared to O(N)
complexity for .some
) (与
.some
O(N)
复杂度相比, Set
具有O(1)
查找时间)
const e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}] const f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}] const qIds = new Set(e.map(({ qId }) => qId)); console.log(f.filter(({ qId }) => qIds.has(qId)));
i hope you need to compare on qId.. 我希望您需要在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)
You can use Array.filter()
and Array.some()
in combination to get that result: 您可以结合使用
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);
You could check if array e
has the same qId
value for filtering f
. 您可以检查数组
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.