把多维数组拍平到指定深度,3 种写法 + 完整示例,复制即用。
一、原生 flat
[1, [2, [3, 4]]].flat(2); // [1, 2, 3, 4]
[1, [2, [3, 4]]].flat(); // 默认深度 1 -> [1, 2, [3, 4]]
二、递归手写(任意深度)
function flatDeep(arr, depth = 1) {
return depth > 0
? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, depth - 1) : val), [])
: arr.slice();
}
flatDeep([1, [2, [3, 4]]], 2); // [1, 2, 3, 4]
三、循环 + 栈(高性能)
function flatStack(arr, depth = 1) {
const stack = arr.map(item => [item, depth]);
const res = [];
while (stack.length) {
const [item, d] = stack.pop();
if (Array.isArray(item) && d > 0) {
stack.push(...item.map(el => [el, d - 1]));
} else {
res.push(item);
}
}
return res.reverse();
}
flatStack([1, [2, [3, 4]]], 2); // [1, 2, 3, 4]
四、速查表
写法 | 深度 | 场景 |
---|---|---|
.flat() | 固定 | 现代浏览器 |
递归 | 任意 | 兼容旧环境 |
栈 | 任意 | 大数组高性能 |
复制即用,无需依赖!