Passing array of arrays to intersection lodash
I have an array of arrays containing objects:
let data = [[{a:0}, {b:1}], [{a:1}, {b:1}]]
Now I would like to make lodash intersect 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 am getting the same result.
Is there an easy way to pass all arrays from data to the intersection function? My initial thought was to use .map, but this returns a different array ...
source to share
You can just spread the array.
intersection(...arrayOfarrays);
Or, in a pre-ES6 environment, use apply :
intersection.apply(null, arrayOfArrays);
Or, you can convert intersect
to a function with extended arguments:
const intersectionArrayOfArrays = _.spread(_.intersection);
intersectionArrayOfArrays(arrayOfArrays);
Remember that this intersection in lodash does not automatically work on arrays of objects .
You can use intersectionBy if you want to intersect by 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>
source to share