Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

why not use reduce ?

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

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);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top