獲取在陣列 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 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.