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

Nandeep Mali picture Nandeep Mali · Apr 26, 2013 · Viewed 14.8k times · Source

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.

Answer

Nandeep Mali picture Nandeep Mali · Apr 26, 2013

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