我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
以下是Typescript中最快的解决方案,它也适用于具有多层嵌套的数组:
export function flatten<T>(input: Array<any>, output: Array<T> = []): Array<T> {
for (const value of input) {
Array.isArray(value) ? flatten(value, output) : output.push(value);
}
return output;
}
以及:
const result = flatten<MyModel>(await Promise.all(promises));
其他回答
[1,[2,3],[4,[5,6]]].reduce(function(p, c) {
return p.concat(c instanceof Array ?
c.reduce(arguments.callee, []) :
[c]);
}, []);
要展平单个元素数组的数组,不需要导入库,简单的循环是最简单和最有效的解决方案:
for (var i = 0; i < a.length; i++) {
a[i] = a[i][0];
}
对反对选民:请阅读问题,不要因为它不适合你的不同问题而反对投票。对于所问的问题,此解决方案是最快和最简单的。
我提出了两个没有递归的简短解决方案。从计算复杂性的角度来看,它们不是最优的,但在一般情况下工作良好:
let a = [1, [2, 3], [[4], 5, 6], 7, 8, [9, [[10]]]];
// Solution #1
while (a.find(x => Array.isArray(x)))
a = a.reduce((x, y) => x.concat(y), []);
// Solution #2
let i = a.findIndex(x => Array.isArray(x));
while (i > -1)
{
a.splice(i, 1, ...a[i]);
i = a.findIndex(x => Array.isArray(x));
}
最好是以递归的方式执行,这样如果另一个数组中还有另一个,就可以很容易地过滤。。。
const flattenArray = arr =>
arr.reduce(
(res, cur) =>
!Array.isArray(cur)
? res.concat(cur)
: res.concat(flattenArray(cur)), []);
你可以这样称呼它:
flattenArray([[["Alireza"], "Dezfoolian"], ["is a"], ["developer"], [[1, [2, 3], ["!"]]]);
结果如下:
["Alireza", "Dezfoolian", "is a", "developer", 1, 2, 3, "!"]
如何使用JavaScript 1.8的reduce(callback[,initialValue])方法
list.reduce((p,n) => p.concat(n),[]);
能胜任这项工作。