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...
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With