Welcome to Michael's Blog! 🎉 currently Renew and moving old post 🫠

Array Flatten - extend Array.prototype.myFlat

Implementation of array flattening by extending Array prototype

Loading comments...

Array Flatten Implementation

難度:Easy

實作一個 Array.prototype.myFlat 方法,將多維陣列轉換成一維陣列

example:
Input: [1, 2, [3, 4, 5]]
Output: [1, 2, 3, 4, 5]

Input: [1, [2, [3, [4, [5]]]]]
Output: [1, 2, 3, 4, 5]

解題重點

  1. 使用 forEach 遍歷陣列
  2. 使用 concat 合併陣列
  3. 使用遞迴處理巢狀陣列

基本實作

使用 forEach 和 concat 的解法:

// eslint-disable-next-line no-extend-native
Array.prototype.myFlat = function () {
  const result: any[] = [];

  this.forEach((item) => {
    if (Array.isArray(item)) {
      result = result.concat(item.myFlat());
    } else {
      result.push(item);
    }
  });

  return result;
};

程式碼解析

  1. 初始化結果陣列
    const result: any[] = [];
    
  2. 遍歷處理每個元素
    this.forEach((item) => {
      if (Array.isArray(item)) {
        // 如果是陣列,遞迴處理
        result = result.concat(item.myFlat());
      } else {
        // 如果不是陣列,直接加入
        result.push(item);
      }
    });
    

使用範例

// 一般陣列
console.log([1, 2, 3, 4, 5].myFlat());
// [1, 2, 3, 4, 5]

// 二維陣列
console.log([1, 2, [3, 4, 5]].myFlat());
// [1, 2, 3, 4, 5]

// 多維陣列
console.log([1, [2, [3, [4, [5]]]]].myFlat());
// [1, 2, 3, 4, 5]

實作重點

  1. 遞迴處理
    • 使用 Array.isArray() 判斷
    • 遞迴呼叫 myFlat()
  2. 陣列合併
    • 使用 concat 合併結果
    • 使用 push 加入元素
  3. 注意事項
    • 處理空陣列情況
    • 確保遞迴終止條件

其他解法

字串轉換法(僅適用於數字陣列)

這是一個非常簡潔的解法,但是有對應的限制,使用場景要先確認好

function flattenOnlyNumbers(array: number[]) {
  return array
    .toString() // 轉成字串,自動用逗號分隔 [1, [2, [3]]] -> "1,2,3"
    .split(',') // 分割成字串陣列 ["1", "2", "3"]
    .map(Number); // 轉回數字 [1, 2, 3]
}

// 使用範例
console.log(flattenOnlyNumbers([1, [2, [3, [4, [5]]]]])); // [1, 2, 3, 4, 5]

解法比較表

解法優點缺點適用場景
遞迴 + forEach通用性強、可讀性好程式碼較長一般使用
字串轉換程式碼最簡潔只能處理數字純數字陣列
原生 flat()效能最佳、簡單瀏覽器支援度實務開發
Loading comments...