35

I have an array of arrays:

var selected = [[1, 4, 5, 6], [1, 2, 3, 5, 7], [1, 4, 5, 6], [1, 7]];

Underscore.js has convenient union and intersection methods but they work on passing each array individually as arguments.

How would I go about it if the number of arrays on which the set operations are to be performed is arbitrary?

This question addresses something similar but it is for an array containing objects.

4 Answers 4

60

One can use apply to pass an arbitrary number of arguments to a method.

For union:

// Outputs [1, 4, 5, 6, 2, 3, 7]
var selectedUnion = _.union.apply(_, selected);

For intersection:

// Outputs [1]
var selectedIntersection = _.intersection.apply(_, selected);
3
  • 2
    Any reason for passing in _ as the first argument? I understand that it sets 'this' in the function, but why not use 'null' or just 'this'. Can't say I totally understand 'this' in this context.
    – Lukus
    Nov 26, 2013 at 1:52
  • Good point. I don't think it affects anything in this use case. I think it was just an OCD to make the statement appear semantically better. :) Dec 2, 2013 at 6:08
  • 3
    This is great, but how do we use this in a _.chain ? Jul 24, 2015 at 5:41
5

why not use reduce ?

_.reduce(selected,function(result,a){
    return _.intersection(result,a);
});
4

var centrifuge = _.spread(_.intersection);

alert(centrifuge([
  [1, 4, 5, 6],
  [1, 2, 3, 5, 7],
  [1, 4, 5, 6],
  [1, 7]
]))


alert(centrifuge([
  [1, 4, 5, 6],
  [1, 2, 4, 6, 3, 5, 7]
]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

var centrifuge = .spread(.intersection);

0
0

The simplest way I could find: _.union(...arrays).

This works in both Underscore.js and in Lodash.

The only major disadvantage I can think of is that it uses array spread syntax, which won't work in Internet Explorer (unless you are using a tool like Babel to translate it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.