使用lodash合并数组中的数组

5
我可以使用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);
});

你尝试过使用 _.flatten 吗? - Bergi
没问题,刚刚测试通过 .union(.flatten(x)) - user2936008
1
请查看 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce 中的“将数组展平”示例。它正好符合您的要求:D - Huy Tran
4个回答

6

为什么我们要将 null 作为参数传递? - user2936008
1
因为我们不需要传递 this(参见 apply 定义)。 - stdob--

3

对我来说,这个答案很有效。虽然其他答案也有用,但是当我查看其他帖子时,他们只是使用了lodash。我不知道在该帖子提供的所有答案中使用哪种语法最好。目前,我使用以下方法:

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

感谢大家的回答。:)

3
我能想到的最简单的解决方案就是只使用concat:
Array.prototype.concat.apply([], [ [1,2,3,4], [5,6,7],[], [8,9], []]);

将会产生...
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Concat 不会移除重复项,而是使用 lodash union - stdob--
啊,我错过了应该删除重复项的部分。 - David Johnson

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接