简体   繁体   English

如何使用Underscore.js对数组数组执行联合或交集

[英]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. Underscore.js具有方便的并集和交集方法,但它们可以将每个数组作为参数单独传递。

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. 可以使用apply将任意数量的参数传递给方法。

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

_.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); var centrifuge = .spread( .intersection);

The simplest way I could find: _.union(...arrays) . 我能找到的最简单的方法: _.union(...arrays) . _.union(...arrays)

This works in both Underscore.js and in Lodash. 这适用于Underscore.js和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). 我能想到的唯一主要缺点是它使用数组扩展语法 ,这在Internet Explorer中不起作用(除非你使用像Babel这样的工具来翻译它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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