將一個數組展平為 Javascript。


我們需要編寫一個 JavaScript 陣列函式,該函式接受一個巢狀陣列,並返回一個包含陣列中所有元素的陣列,不包含任何巢狀。

例如 −

//if the input is:
const arr = [[1, 2, 3], [4, 5], [6]];
//then the output should be:
const output = [1, 2, 3, 4, 5, 6];

因此,讓我們為這個函式編寫程式碼 −

方法 1:使用遞迴

這裡我們將迴圈遍歷原始的巢狀陣列,並遞迴地將巢狀元素元素推送到一個新陣列中。

示例

const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
   let res = [];
   for(let i = 0; i < this.length; i++){
      if(Array.isArray(this[i])){
         res.push(...this[i].flatten());
      } else {
         res.push(this[i]);
      };
   };
   return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());

方法 2:使用 Arrray.prototype.reduce()

這裡我們將使用 reduce() 方法構造一個類似這樣的新陣列 −

示例

const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
   return this.reduce((acc, val) => {
      return acc.concat(...val);
   }, []);
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());

輸出

這兩種方法的控制檯輸出為 −

[ 1, 2, 3, 4, 5, 6 ]

更新於: 2020 年 8 月 25 日

233 次瀏覽

開啟你的職業

完成課程,獲得認證

開始
廣告