简体   繁体   中英

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...

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> 

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