Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of arrays into lodash intersection

I have an array of arrays that contain objects:

let data = [[{a:0}, {b:1}], [{a:1}, {b:1}]]

Now I would want to make a lodash intersection of these two arrays, returning [{b:1}]

When I do this:

import {intersection} from 'lodash'

return intersection([{a:0}, {b:1}], [{a:1}, {b:1}])

the result is correct.

But when I do

return intersection(data)

I just get the same result back.

Is there an easy way to pass all the arrays from data to the intersection function? My initial thought was to use .map, but this returns another array...

like image 976
Miha Šušteršič Avatar asked Jun 15 '17 15:06

Miha Šušteršič


1 Answers

You could just spread the array.

intersection(...arrayOfarrays);

Or, in a pre ES6 environment, use apply:

intersection.apply(null, arrayOfArrays);

Or, you could convert intersect into a function with spread-out arguments:

const intersectionArrayOfArrays = _.spread(_.intersection);
intersectionArrayOfArrays(arrayOfArrays);

Be aware though that intersection in lodash doesn't automatically work on arrays of objects.

You could use intersectionBy, if you want to intersect on the property b:

const arrayOfArrays = [[{a:0}, {b:1}], [{a:1}, {b:1}]];
console.log(
  _.intersectionBy(...arrayOfArrays, 'b')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

or intersectionWith, if you want to intersect on the same objects by reference or deep comparison:

const a1 = {a: 0};
const a2 = {a: 1};
const b = {b: 1};
const arrayOfArrays = [[a1, b], [a2, b]];

// reference comparison
console.log(
  _.intersectionWith(...arrayOfArrays, (a, b) => a === b)
)

// deep equality comparison
console.log(
  _.intersectionWith(...arrayOfArrays, _.isEqual)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 147
nem035 Avatar answered Nov 14 '22 01:11

nem035