本文翻译自:Merge/flatten an array of arrays
I have a JavaScript array like: 我有一个像这样的JavaScript数组:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
How would I go about merging the separate inner arrays into one like: 我将如何将单独的内部数组合并为一个类似的数组:
["$6", "$12", "$25", ...]
#1楼
参考:https://stackoom.com/question/jaUL/合并-展平数组
#2楼
You can use concat
to merge arrays: 您可以使用concat
合并数组:
var arrays = [ ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"] ]; var merged = [].concat.apply([], arrays); console.log(merged);
Using the apply
method of concat
will just take the second parameter as an array, so the last line is identical to this: 使用concat
的apply
方法将仅将第二个参数作为数组,因此最后一行与此相同:
var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
There is also an experimental Array.prototype.flat()
method (not yet part of the ECMAScript standard) which you could use to flatten the arrays, although it is only available in Node.js starting with version 11, and not at all in Edge . 还有一个实验性的Array.prototype.flat()
方法(尚不是ECMAScript标准的一部分),您可以使用它来展平数组,尽管它仅在从版本11开始的Node.js中可用,而在所有版本中均不可用。边缘 。
const arrays = [ ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"] ]; const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. console.log(merge3);
#3楼
To flatten an array of single element arrays, you don't need to import a library, a simple loop is both the simplest and most efficient solution : 要展平单元素数组的数组,不需要导入库,简单的循环既是最简单也是最有效的解决方案:
for (var i = 0; i < a.length; i++) {
a[i] = a[i][0];
}
To downvoters: please read the question, don't downvote because it doesn't suit your very different problem. 致拒绝投票的人:请阅读问题,不要拒绝投票,因为它不适合您的非常不同的问题。 This solution is both the fastest and simplest for the asked question. 对于提出的问题,此解决方案既最快又最简单。
#4楼
That's not hard, just iterate over the arrays and merge them: 这并不难,只需遍历数组并合并它们:
var result = [], input = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"]];
for (var i = 0; i < input.length; ++i) {
result = result.concat(input[i]);
}
#5楼
You can use Underscore : 您可以使用Underscore :
var x = [[1], [2], [3, 4]];
_.flatten(x); // => [1, 2, 3, 4]
#6楼
If you only have arrays with 1 string element: 如果只有带有1个字符串元素的数组:
[["$6"], ["$12"], ["$25"], ["$25"]].join(',').split(',');
will do the job. 会做的工作。 Bt that specifically matches your code example. Bt与您的代码示例特别匹配。