Get the Item that Appears the Most Times in an Array in JavaScript



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
Updated on: 2020-08-20T06:34:53+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements