將相同條目分組到子陣列中 - JavaScript


比如說,我們有一個數字陣列,其中包含有相同的條目。我們需要寫一個函式來接受此陣列,將所有相同的條目分組到一個子陣列中,並返回以這種方式形成的新陣列。

例如:如果輸入陣列是 -

const arr = [234, 65, 65, 2, 2, 234];

則輸出應為 -

const output = [[234, 234], [65, 65], [2, 2]];

我們將使用一個散列表來跟蹤已經出現的元素,並使用 for 迴圈迭代陣列。

示例

以下是程式碼 -

const arr = [234, 65, 65, 2, 2, 234];
const groupArray = arr => {
   const map = {};
   const group = [];
   for(let i = 0; i < arr.length; i++){
      if(typeof map[arr[i]] === 'number'){
         group[map[arr[i]]].push(arr[i]);
      }else{
         //the push method returns the new length of array
         //and the index of newly pushed element is length-1
         map[arr[i]] = group.push([arr[i]])-1;
      }
   };
   return group;
}
console.log(groupArray(arr));

輸出

這將在控制檯中生成以下輸出 -

[ [ 234, 234 ], [ 65, 65 ], [ 2, 2 ] ]

更新於: 2020-9-18

126 次檢視

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.