Question

I have an arbitrary length array of arrays. I want to compute the intersection.

I tried doing this in two ways that I thought were equivalent, but they produced different output.

What is the difference between:

var a = [[1,2,3,4,5], [3, 4,5,6,7], [4,5,6,7,8]]
_.foldl(a, function(a, b) { return _.intersection(a, b) } )
// Works as expected -> [4, 5]

And this:

var a = [[1,2,3,4,5], [4,5,6,7], [5,6,7,8]]
_.foldl(a, _.intersection )
// Does not work -> []

?

And is there a better way to do it?

Was it helpful?

Solution 2

I think the best way to do it would be using apply and intersection:

var a = [[1,2,3,4,5], [3, 4,5,6,7], [4,5,6,7,8]];
_.intersection.apply(null, a);
// -> returns [ 4, 5 ]

OTHER TIPS

You don't need a fold here.

Underscore's intersection already can take multiple arrays.

so _.intersection.apply(null, a)

or _.intersection([1, 2, 3, 4, 5], [4, 5, 6, 7], [5, 6, 7, 8])

will work.

_.intersection takes any number of arrays.

Simply use

_.intersection(arrayA, arrayB, arrayC, ...);

Or if you have an array of arrays

_.intersection.apply(_, arrayOfArrays);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top