Get the item that appears the most times in an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we are required to write a function that takes in an array of string / number literals and returns the index of the item that appears for the most number of times. We will iterate over the array and prepare a frequencyMap and from that map we will return the index that makes most appearances.

The code for doing so will be −

Example

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));

Output

The output in the console will be −

6
1
raja
Published on 20-Aug-2020 06:34:00
Advertisements