数组内使用lodash数组的联合

我怎样才能使用lodash数组内的数组?

例如:

input:

var x = [ [1,2,3,4], [5,6,7], [], [8,9], [] ]; 

预期产出:

 x = [1,2,3,4,5,6,7,8,9]; 

目前我的代码执行以下操作:

 return promise.map(someObjects, function (object)) { return anArrayOfElements(); }).then(function (arrayOfArrayElements) { // I tried to use union but it can apply only on two arrays _.union(arrayOfArrayElements); }); 

使用apply方法传递数组值作为参数:

 var union = _.union.apply(null, arrayOfArrayElements); 

[ https://jsfiddle.net/qe5n89dh/ ]

我能想到的最简单的解决scheme就是使用concat

 Array.prototype.concat.apply([], [ [1,2,3,4], [5,6,7],[], [8,9], []]); 

将产生…

 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 

为我工作的答案,所有其他的答案工作,但是当我检查其他职位,他们只是使用loadash。 我dnt知道什么是最好的语法来使用在post中提供的所有答案。 现在使用下面的方法

 _.uniq(_.flatten(x)); // x indicates arrayOfArrayObjects // or, using chain _(x).flatten().uniq().value(); 

谢谢大家的答案。 🙂

只需使用本地函数reduce就可以减less它

 arr.reduce(function(previousValue, currentValue) { return previousValue.concat(currentValue); }, []); 

这将对数组中的每个元素应用reducecallback函数,并针对您所显示的用例将其减less。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce