簡體   English   中英

Underscore.js-帶有交集的foldl

[英]Underscore.js - foldl with intersection

我有一個任意長度的數組數組。 我想計算交集。

我嘗試以我認為是等效的兩種方式進行此操作,但是它們產生了不同的輸出。

之間有什么區別?

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]

和這個:

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

還有更好的方法嗎?

您不需要在這里折。

下划線的交點已可以采用多個數組。

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

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

將工作。

_.intersection采用任意數量的數組。

只需使用

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

或者如果您有一個數組數組

_.intersection.apply(_, arrayOfArrays);

我認為最好的方法是使用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