Find the most frequent number in the array and how many times it is repeated in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals and finds the most frequent number in the array and how many times it is repeated.

Example

The code for this will be −

const arr = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
const findFrequency = (arr = []) => {
   const count = {};
   const max = arr.reduce((acc, val, ind) => {
      count[val] = (count[val] || 0) + 1;
      if (!ind || count[val] > count[acc[0]]) {
         return [val];
      };
      if (val !== acc[0] && count[val] === count[acc[0]]) {
         acc.push(val);
      };
      return acc;
   }, undefined);
   return {
      max, count
   };
}
console.log(findFrequency(arr));

Output

And the output in the console will be −

{
   max: [ '4' ],
   count: { '1': 3, '2': 2, '3': 2, '4': 5, '9': 1, '13': 1 }
}
raja
Published on 23-Nov-2020 10:09:35
Advertisements