Finding number of occurrences of the element appearing most number of times in JavaScript


We are required to write a JavaScript function that takes in an array of literals and returns the count of elements that appears for the most number of times in the array.

Example

The code for this will be −

let arr = [2, 8, 4, 8, 6, 4, 7, 8];
const countOccurence = arr => {
   const max = arr.reduce((acc, val) => {
      return Math.max(acc, val);
   }, -Infinity);
   const count = arr.filter(el => {
      return el === max;
   });
   const { length } = count;
   return length;
};
console.log(countOccurence(arr));

Output

The output in the console −

3

Updated on: 12-Oct-2020

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements