javascript 如何使用 Underscore.js 对数组数组执行并集或交集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16229479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform union or intersection on an array of arrays with Underscore.js
提问by Nandeep Mali
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 addressessomething similar but it is for an array containing objects.
回答by Nandeep Mali
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);
回答by Aladdin Mhemed
why not use reduce?
为什么不使用减少?
_.reduce(selected,function(result,a){
return _.intersection(result,a);
});
回答by duality
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 离心机 = .spread(.intersection);
回答by Elias Zamaria
The simplest way I could find: _.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 之类的工具来翻译它)。