js数组扁平化方法

245 阅读1分钟
  • ES6的 flat( ) 方法
const arr = [1,2,[3,4,[5,6]],7]
arr.flat(Infinity) //[1,2,3,4,5,6,7] Infinity展开任意深度的嵌套数组
  • 循环递归(参数控制扁平化深度)
const arr = [1,2,[3,4,[5,6]],7]
const eachFlat = (arr = [], depth = 1) => {
  const result = []; // 缓存递归结果
  // 开始递归
  (function flat(arr, depth) {
    // forEach 会自动去除数组空位
    arr.forEach((item) => {
      // 控制递归深度
      if (Array.isArray(item) && depth > 0) {
        // 递归数组
        flat(item, depth - 1)
      } else {
        // 缓存元素
        result.push(item)
      }
    })
  })(arr, depth)
  // 返回递归结果
  return result;
}
eacheFlat(arr,Infinity) //[1,2,3,4,5,6,7] Infinity可替换为任意正整数值
  • reduce方法
const arr = [1,2,[3,4,[5,6]],7]
const flatten = (arr, deep = 1) => {
    if (deep <= 0) return arr;
    return arr.reduce((res, curr) => res.concat(Array.isArray(curr) ? flatten(curr, deep - 1) : curr), [])
}
flatten(arr,Infinity) //[1,2,3,4,5,6,7]  Infinity可替换为任意正整数值
  • Generate函数
const arr = [1,2,[3,4,[5,6]],7]
function* flatten(array) {
    for (const item of array) {
        if (Array.isArray(item)) {
            yield* flatten(item);
        } else {
            yield item;
        }
    }
}
[...flatten(arr)]  //  [1,2,3,4,5,6,7]
  • 使用堆栈stack避免递归
const arr = [1,2,[3,4,[5,6]],7]
function flatten(arr) {
  const stack = [...arr];
  const res = [];
  while (stack.length) {
    // 使用 pop 从 stack 中取出并移除值
    const next = stack.pop();
    if (Array.isArray(next)) {
      // 使用 push 送回内层数组中的元素,不会改动原始输入
      stack.push(...next);
    } else {
      res.push(next);
    }
  }
  // 反转恢复原数组的顺序
  return res.reverse();
}
flatten(arr)  //  [1,2,3,4,5,6,7]
  • while + some
const arr = [1,2,[3,4,[5,6]],7]
function flatten(arr) {
  while (arr.some(item=> Array.isArray(item))) {
    arr = [].concat(...arr)
  }
  return arr
}
flatten(arr)  //  [1,2,3,4,5,6,7]