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
.
For the least complexity, turn the e
array's qId
s into a Set
for quick lookup first. ( Set
s have O(1)
lookup time, compared to O(N)
complexity for .some
)
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..
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:
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
.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.