JavaScript 从浅入深 100 题训练计划--(4)扁平化数组

题目:将多维数组扁平化

// 输入
[1, [2, [3, [4, 5]]]]
// 输出
[1, 2, 3, 4, 5]

要求:分别用递归、迭代、和 flat 方法实现

 

const arr = [1, 2, 4, [5, 6, [7, 8]]]

function flatCustom(arr) {
  let list = [];
  let len = arr.length;
  for (let i = 0; i < len; i++) {
    if (Array.isArray(arr[i])) {
      list = list.concat(flatCustom(arr[i]))
    } else {
      list.push(arr[i])
    }
  }
  return list;
}

function flatC(arr) {
  let stack = [...arr]
  let list = []
  while (stack.length) {
    const item = stack.pop()
    if (Array.isArray(item)) {
      stack.push(...item)
    } else {
      list.push(item)
    }
  }
  return list.reverse();
}

function flatReduce(arr) {
  return arr.reduce((acc, cur) =>
    acc.concat(Array.isArray(cur) ? flatReduce(cur) : cur)
    , [])
}
function flattenDepth(arr, depth = 1) {
  if (depth === 0) return arr.slice();

  return arr.reduce((acc, cur) => {
    if (Array.isArray(cur) && depth > 0) {
      return acc.concat(flattenDepth(cur, depth - 1));
    }
    return acc.concat([cur]);
  }, []);
}

console.log(flattenDepth(arr, 1)); // [1, 2, [3, [4]]]
console.log(flattenDepth(arr, 2)); // [1, 2, 3, [4]]
console.log(flattenDepth(arr, Infinity)); // [1, 2, 3, 4]

console.log(flatCustom(arr), 'flat', flatC(arr), arr.flat(Infinity), flatReduce(arr))
console.log(flatCustom(arr), 'flat', flatC(arr), arr.flat(Infinity), flatReduce(arr))

  

  

  

  

 

 

posted @ 2026-07-18 14:40  小新的蜡笔  阅读(2)  评论(0)    收藏  举报