JavaScript 中階

請實踐陣列扁平化 (flatten)

AI 練習作答

什麼是陣列扁平化?

巢狀陣列展開成一維陣列的操作。

// 輸入
[1, [2, [3, [4]], 5]]

// 輸出(完全扁平化)
[1, 2, 3, 4, 5]

方法一:Array.prototype.flat()(ES2019)

[1, [2, [3]]].flat();     // [1, 2, [3]](預設深度 1)
[1, [2, [3]]].flat(2);    // [1, 2, 3]
[1, [2, [3]]].flat(Infinity); // [1, 2, 3](完全扁平)

方法二:遞迴實現

function flatten(arr) {
  return arr.reduce((result, item) => {
    if (Array.isArray(item)) {
      return result.concat(flatten(item));
    }
    return result.concat(item);
  }, []);
}

flatten([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5]

方法三:指定深度的遞迴

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

flattenDepth([1, [2, [3, [4]]]], 2); // [1, 2, 3, [4]]

方法四:Stack 迭代(非遞迴,效能較好)

function flattenIterative(arr) {
  const stack = [...arr];
  const result = [];
  while (stack.length) {
    const item = stack.pop();
    if (Array.isArray(item)) {
      stack.push(...item);
    } else {
      result.unshift(item);
    }
  }
  return result;
}

方法五:flatMap(扁平化 + map)

// 只扁平化一層,但可搭配 map 使用
[1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分