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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 12-Oct-2020 11:26:33
Advertisements