Reputation: 4456
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
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
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
Reputation: 3971
why not use reduce ?
_.reduce(selected,function(result,a){
return _.intersection(result,a);
});
Upvotes: 5
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