我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
您可以继续使用Array.flat()方法来实现这一点,即使数组嵌套得更多。
[1,2,3,[2]].flat()
相当于
[1,2,3,[2]].flat(1)
所以当你的筑巢增加时,你可以继续增加数量。
eg:
[1,[2,[3,[4]]]].flat(3) // [1, 2, 3, 4]
如果您不确定嵌套的级别,可以只传递Infinity作为参数
[1,2,3,[2,[3,[3,[34],43],[34]]]].flat(Infinity) //[1, 2, 3, 2, 3, 3, 34, 43, 34]
其他回答
最好是以递归的方式执行,这样如果另一个数组中还有另一个,就可以很容易地过滤。。。
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, "!"]
这是一个基于artif3x答案的Typescript版本,为Scala粉丝提供了flatMap的额外实现。
function flatten<T>(items: T[][]): T[] {
return items.reduce((prev, next) => prev.concat(next), []);
}
function flatMap<T, U>(items: T[], f: (t: T) => U[]): U[] {
return items.reduce((prev, next) => prev.concat(f(next)), new Array<U>());
}
以下是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));
以下代码将压平深度嵌套的数组:
/**
* [Function to flatten deeply nested array]
* @param {[type]} arr [The array to be flattened]
* @param {[type]} flattenedArr [The flattened array]
* @return {[type]} [The flattened array]
*/
function flattenDeepArray(arr, flattenedArr) {
let length = arr.length;
for(let i = 0; i < length; i++) {
if(Array.isArray(arr[i])) {
flattenDeepArray(arr[i], flattenedArr);
} else {
flattenedArr.push(arr[i]);
}
}
return flattenedArr;
}
let arr = [1, 2, [3, 4, 5], [6, 7]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]
arr = [1, 2, [3, 4], [5, 6, [7, 8, [9, 10]]]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
如果您的编码环境支持ES6(ES2015),那么您不需要编写任何递归函数或使用map、reduce等数组方法。
一个简单的排列运算符(…)将帮助您将一个数组展平为单个数组
eg:
const data = [[1, 2, 3], [4, 5],[2]]
let res = []
data.forEach(curSet=>{
res = [...res,...curSet]
})
console.log(res) //[1, 2, 3, 4, 5, 2]