我有以下数组格式,我想使用lodash或普通的js组合它。
var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]
我想将所有这些组合成一个,输出应该在数组下面。
testArray = [1,2,3,4,5,6,7,8,9,10]
答案 0 :(得分:2)
您可以将flattenDeep
与_.union
合并。如果需要,应用排序
var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]],
result = _.chain(testArray)
.flattenDeep()
.union();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
答案 1 :(得分:1)
使用ES6,您可以使用展开式语法...
和Set
var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]
var result = [...new Set([].concat(...testArray))];
console.log(result)
答案 2 :(得分:1)
将_.union()
应用于父数组:
var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]];
var result = _.union.apply(_, testArray);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
如果支持ES6,请使用array spread:
const testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]];
const result = _.union(...testArray);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
答案 3 :(得分:0)
您只需致电_.union.apply(null, arrays)
即可。这里记录在案:
https://lodash.com/docs/#union
> var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]
> lodash.union.apply(null, testArray)
[ 1, 2, 3, 4, 5, 6, 7, 8, 10, 9 ]
应用技巧是将数组数组转换为函数调用参数。如果您也需要对它进行排序,您可以将.sort()
放在最后。
答案 4 :(得分:0)
如果你需要,只需要ES5:
var flattened = Object.keys(testArray.reduce(function(acc, cur) {
cur.forEach(function(v) {acc[v] = true;});
return acc;
}, {})).sort(function(a, b) {return a - b;});