使用 lodash 的数组内部数组联合
Union of array inside array using lodash
如何使用 lodash 合并数组中的数组?
例如:
Input:
var x = [ [1,2,3,4], [5,6,7], [], [8,9], [] ];
Expected output:
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);
});
只需使用本机函数减少它reduce
arr.reduce(function(previousValue, currentValue) {
return previousValue.concat(currentValue);
}, []);
这会将 reduce 回调函数应用于数组的每个元素,并针对您展示的用例对其进行归约。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
使用apply
方法将数组值作为参数传递:
var union = _.union.apply(null, arrayOfArrayElements);
我能想到的最简单的解决方案就是使用 concat
:
Array.prototype.concat.apply([], [ [1,2,3,4], [5,6,7],[], [8,9], []]);
将产生...
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
对我有效的答案,所有其他答案都有效,但是当我检查其他 post 他们只是使用 loadash。我不知道 post 中提供的所有答案的最佳语法是什么。
现在使用下面的方法
_.uniq(_.flatten(x)); // x indicates arrayOfArrayObjects
// or, using chain
_(x).flatten().uniq().value();
感谢大家的回答。 :)
如何使用 lodash 合并数组中的数组?
例如:
Input:
var x = [ [1,2,3,4], [5,6,7], [], [8,9], [] ];
Expected output:
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);
});
只需使用本机函数减少它reduce
arr.reduce(function(previousValue, currentValue) {
return previousValue.concat(currentValue);
}, []);
这会将 reduce 回调函数应用于数组的每个元素,并针对您展示的用例对其进行归约。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
使用apply
方法将数组值作为参数传递:
var union = _.union.apply(null, arrayOfArrayElements);
我能想到的最简单的解决方案就是使用 concat
:
Array.prototype.concat.apply([], [ [1,2,3,4], [5,6,7],[], [8,9], []]);
将产生...
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
对我有效的答案,所有其他答案都有效,但是当我检查其他 post 他们只是使用 loadash。我不知道 post 中提供的所有答案的最佳语法是什么。 现在使用下面的方法
_.uniq(_.flatten(x)); // x indicates arrayOfArrayObjects
// or, using chain
_(x).flatten().uniq().value();
感谢大家的回答。 :)