分組和排序 2D 陣列


假設我們有一個這樣的數字二維陣列 −

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

我們要求編寫一個 JavaScript 函式,將所有相同的數字分組到其自己的獨立子陣列中,然後函式應該對組陣列進行排序,按升序排列子陣列。

因此,最終新陣列應如下所示 −

const output = [
   [1, 1, 1],
   [2, 2, 2],
   [4], [3],
   [5]
];

示例

程式碼如下 −

const arr = [
   [1, 3, 2],
   [5, 2, 1, 4],
   [2, 1]
];
const groupAndSort = arr => {
   const res = [];
   const map = Object.create(null);
   Array.prototype.forEach.call(arr, item => {
      item.forEach(el => {
         if (!(el in map)) {
            map[el] = [];
            res.push(map[el]);
         };
         map[el].push(el);
      });
   });
   res.sort((a, b) => {
      return a[0] - b[0];
   });
   return res;
};
console.log(groupAndSort(arr));

輸出

控制檯中的輸出 −

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

更新於: 10 月 12 日,2020 年

724 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.