📊多维数组扁平化:flat 还是手写?看完秒懂

71 阅读1分钟

把多维数组拍平到指定深度,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()固定现代浏览器
递归任意兼容旧环境
任意大数组高性能

复制即用,无需依赖!

解锁更多前端基础教程、实战技巧、避坑指南
关注同名公众号 & 博客 前端干货每天见