Nandeep Mali
Nandeep Mali

Reputation: 4456

How to perform union or intersection on an array of arrays with Underscore.js

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.

Upvotes: 35

Views: 15885

Answers (4)

Elias Zamaria
Elias Zamaria

Reputation: 101153

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

Upvotes: 0

duality
duality

Reputation: 1223

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

Upvotes: 4

Aladdin Mhemed
Aladdin Mhemed

Reputation: 3971

why not use reduce ?

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

Upvotes: 5

Nandeep Mali
Nandeep Mali

Reputation: 4456

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

Upvotes: 60

Related Questions