简体   繁体   中英

lodash - using intersectionWith to get intersection of arrays of objects results in a uniqueness issue

I am trying to intersect 2 arrays of objects by some attribute using Lodash intersectWith .

For example:

var objects = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

// Intersect by objects with the same value for 'x'
_.intersectionWith(objects, others, (obj, oth) => obj.x === oth.x);

Doing so, I'm getting an unexpected result of just 1 object:

[{ x: 1, y: 1 }]

instead of the entire first array:

[{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]

For some reason the intersectionWith function seemingly returns only unique results according to the attribute being compared.

Can anyone explain why this is happening?

Maybe you miss the part of _.intersection :

Creates an array of unique values that are included in all given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array. [ Emphasis by NS]

That means, if you have a checked value of x: 1 , then no more objects with this value are included in the result set.

Lodash documentation on _.intersection :

Creates an array of unique values that are included in all given arrays using SameValueZero for equality comparisons.

Lodash documentation on _.intersectionWith

This method is like _.intersection except that it accepts comparator which is invoked to compare elements of arrays.

It means that your comparator determines uniqueness of values. By comparing only x you make all objects actually the same according to your custom comparator.

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.

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