[英]How to perform union or intersection on an array of arrays with 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.