尋找二維陣列的轉置—— JavaScript


我們需要編寫一個 JavaScript 函式,該函式接受一個二維陣列並返回其轉置陣列。

其程式碼如下 −

方法 1:使用 Array.prototype.forEach()

const arr = [
   [0, 1],
   [2, 3],
   [4, 5]
];

const transpose = arr => {
   const res = [];
   arr.forEach((el, ind) => {
      el.forEach((elm, index) => {
         res[index] = res[index] || [];
         res[index][ind] = elm;

      });
   });
   return res;
};
console.log(transpose(arr));

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

const arr = [
   [0, 1],
   [2, 3],
   [4, 5]
];
const transpose = arr => {

   let res = [];
   res = arr.reduce((acc, val, ind) => {
      val.forEach((el, index) => {

         acc[index] = acc[index] || [];
         acc[index][ind] = el;

      });
      return acc;
   }, [])
   return res;
};

console.log(transpose(arr));

對於這兩種方法,其在控制檯中的輸出為 −

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

更新於: 2020 年 10 月 9 日

187 次瀏覽

開啟您的職業生涯

完成課程,取得認證

開始
廣告
© . All rights reserved.