简体   繁体   English

比较对象javascript的两个数组并删除不相等的值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM