简体   繁体   English

Underscore.js-带有交集的foldl

[英]Underscore.js - foldl with intersection

I have an arbitrary length array of arrays. 我有一个任意长度的数组数组。 I want to compute the intersection. 我想计算交集。

I tried doing this in two ways that I thought were equivalent, but they produced different output. 我尝试以我认为是等效的两种方式进行此操作,但是它们产生了不同的输出。

What is the difference between: 之间有什么区别?

var a = [[1,2,3,4,5], [3, 4,5,6,7], [4,5,6,7,8]]
_.foldl(a, function(a, b) { return _.intersection(a, b) } )
// Works as expected -> [4, 5]

And this: 和这个:

var a = [[1,2,3,4,5], [4,5,6,7], [5,6,7,8]]
_.foldl(a, _.intersection )
// Does not work -> []

?

And is there a better way to do it? 还有更好的方法吗?

You don't need a fold here. 您不需要在这里折。

Underscore's intersection already can take multiple arrays. 下划线的交点已可以采用多个数组。

so _.intersection.apply(null, a) 所以_.intersection.apply(null, a)

or _.intersection([1, 2, 3, 4, 5], [4, 5, 6, 7], [5, 6, 7, 8]) _.intersection([1, 2, 3, 4, 5], [4, 5, 6, 7], [5, 6, 7, 8])

will work. 将工作。

_.intersection takes any number of arrays. _.intersection采用任意数量的数组。

Simply use 只需使用

_.intersection(arrayA, arrayB, arrayC, ...);

Or if you have an array of arrays 或者如果您有一个数组数组

_.intersection.apply(_, arrayOfArrays);

I think the best way to do it would be using apply and intersection : 我认为最好的方法是使用applyintersection

var a = [[1,2,3,4,5], [3, 4,5,6,7], [4,5,6,7,8]];
_.intersection.apply(null, a);
// -> returns [ 4, 5 ]

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

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