检查数组的某些元素是否相同 JavaScript


我们有一个包含一些冗余项目的数组,我们的工作是编写一个函数,该函数接受该数组并将所有相同的项目组合到一个子数组中,并返回由此形成的新数组。

例如 −

//If the input array is:
const arr = [1, 3, 3, 1];
//then the output should be:
const output = [[1, 1], [3, 3]];

我们将使用 HashMap 来跟踪已经发生的元素,并使用 for 循环迭代数组,代码如下 −

示例

const arr = [1, 3, 3, 1];
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));

输出

控制台中的输出将是 −

[ [ 1, 1 ], [ 3, 3 ] ]

更新于: 25-8-2020

319 查看

开启你的职业生涯

完成此课程以获得认证

开始
广告
© . All rights reserved.