简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM