簡體   English   中英

如何使用Underscore.js對數組數組執行聯合或交集

[英]How to perform union or intersection on an array of arrays with Underscore.js

我有一個數組數組:

var selected = [[1, 4, 5, 6], [1, 2, 3, 5, 7], [1, 4, 5, 6], [1, 7]];

Underscore.js具有方便的並集和交集方法,但它們可以將每個數組作為參數單獨傳遞。

如果要執行設置操作的數組的數量是任意的,我該如何處理呢?

這個問題解決了類似的問題,但它適用於包含對象的數組。

可以使用apply將任意數量的參數傳遞給方法。

對於工會:

// Outputs [1, 4, 5, 6, 2, 3, 7]
var selectedUnion = _.union.apply(_, selected);

對於交叉點:

// Outputs [1]
var selectedIntersection = _.intersection.apply(_, selected);

為什么不使用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);

我能找到的最簡單的方法: _.union(...arrays) . _.union(...arrays)

這適用於Underscore.js和Lodash。

我能想到的唯一主要缺點是它使用數組擴展語法 ,這在Internet Explorer中不起作用(除非你使用像Babel這樣的工具來翻譯它)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM