获取在数组 JavaScript 中出现最多次的项


假设要求我们编写一个函数,该函数接收一个字符串/数字常量数组,并返回出现次数最多的项的索引。我们将对数组进行迭代并准备一个频数映射,并从该映射中返回出现次数最多的索引。

执行此操作的代码如下 −

示例

const arr1 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34];
const arr2 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34];
const mostAppearances = (arr) => {
   const frequencyMap = {};
   arr.forEach(el => {
      if(frequencyMap[el]){
         frequencyMap[el]++;
      }else{
         frequencyMap[el] = 1;
      };
   });
   let highest, frequency = 0;
   Object.keys(frequencyMap).forEach(key => {
      if(frequencyMap[key] > frequency){
         highest = parseInt(key, 10);
         frequency = frequencyMap[key];
      };
   });
   return arr.indexOf(highest);
};
console.log(mostAppearances(arr1));
console.log(mostAppearances(arr2));

输出

控制台中的输出将为 −

6
1

更新日期:2020 年 8 月 20 日

307 次浏览

开启您的职业生涯

完成课程即可获得认证

开始
广告