将相同的条目分组到子数组中 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 12:28:17

假设我们有一个包含相同条目的数字数组。我们需要编写一个函数,该函数接收该数组并将所有相同的条目分组到一个子数组中,并返回由此形成的新数组。

例如:如果输入数组是 −

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 ] ]

相关文章


有用资源