简体   繁体   中英

What is the most efficient inverse of lodash _.intersection()

Using lodash , I want to find all the elements between two arrays that are different, basically the opposite or inverse of _.intersection[with|by] . Of course I reviewed _.difference[with|by] but it's not an inverse version of _.intersection as it only compares the first array with the second, rather than comparing them against each other. The closest I was able to get is very cludgy which has motivated me to ask here if I'm missing a more efficient and/or elegant option. I'm only interested in lodash based solutions.

Here is the closest I could come up with to get a unique array of values that are different between both arrays. I'm interested in values with id properties that aren't in both arrays and values with matching id properties but different v properties.

const n = [{id: 0, v: 9.7}, {id: 1, v: 1.7}, {id: 3, v: 2.6}, {id: 4, v: 1.89}]
const o = [{id: 1, v: 1.7}, {id: 3, v: 3.6}, {id: 7, v: 0.89}, {id: 4, v: 1.89}]

_.uniqBy(_.concat(
    _.differenceWith(n, o, _.isEqual), _.differenceWith(o, n, _.isEqual)), 'id')

That code will yield:

[{id: 0, v: 9.7}, {id: 3, v: 2.6}, {id: 7, v: 0.89}]

I found this question after looking for the same thing, but I since came to realize that for my use case - identifying records that don't match, and then why they don't match - it isn't useful to have a list of all differences like that.

That list can't tell me anything I can use, so I would still need to do a further operation to see which array/s are the problem.

So for me, it makes more sense to first check for equality, then to use _.difference twice, because then the result of it yields usable information, eg

if (!_.isEqual(a, b) {
  const idsFromBThatAreNotInA = _.difference(a, b);
  const idsFromAThatAreNotInB = _.difference(b, a);
}

I don't know what the use case of the OP is, so I don't know if this is directly relevant, but maybe it can help others.

_.xorWith is the closest I could think of, but it doesn't work with the example you provided because two objects have an id of 3.

const n = [{id: 0, v: 9.7}, {id: 1, v: 1.7}, {id: 3, v: 2.6}, {id: 4, v: 1.89}]
const o = [{id: 1, v: 1.7}, {id: 3, v: 3.6}, {id: 7, v: 0.89}, {id: 4, v: 1.89}]
_.xorWith(n, o, _.isEqual)

output would be:

[
  { id: 0, v: 9.7 },
  { id: 3, v: 2.6 },
  { id: 3, v: 3.6 },
  { id: 7, v: 0.89 }
]

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