Get greatest repetitive item in array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have an array of Number / String literals that contains some values (some are repetitive as well). Our job is to write a function that returns the element from the array which appears for the greatest number of times in the array.

For example − if the input array is −

const input = ['a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a', 'j',
'a'];

Then the output should be −

'a'

because 'a' gets repeated for the maximum number of times

Therefore, let’s write the code for this. We will use a Map() to keep track of all the elements we encounter and their count, and at last return the element with maximum count like this −

Example

const input = ['m', 'a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a',
'j', 'a'];
const findMaximum = arr => {
   const map = arr.reduce((acc, val) => {
      let count = acc.get(val);
      if(count){
         acc.set(val, ++count);
      } else {
         acc.set(val, 1);
      };
      return acc;
   }, new Map());
   return Array.from(map).reduce((acc, val) => {
      if(val[1] > acc[1]){
         return val;
      };
      return acc;
   }, [0, 0])[0];
};
console.log(findMaximum(input));

Output

The output in the console will be −

a
raja
Updated on 28-Aug-2020 13:47:41

Advertisements