Highest occurrence in an array or first selected in JavaScript


We are required to write a JavaScript function that takes in an array of literal values. Our function should then return the highest occurrence of an array value, and if there's an equal occurrence, we should return the first selected value of the equal occurrences.

const arr = ['25', '50', 'a', 'a', 'b', 'c']

In this case, we should return 'a'

const arr = ['75', '100', 'a', 'b', 'b', 'a']

In this case, I should also get 'a'

Example

The code for this will be −

const arr = ['25', '50', 'a', 'a', 'b', 'c'];
const arr1 = ['75', '100', 'a', 'b', 'b', 'a'];
const getMostFrequentValue = (arr = []) => {
   let count = 0, ind = -1;
   arr.forEach((el, i) => {
      this[el] = this[el] || { count: 0, ind: i };
      this[el].count++;
      if (this[el].count > count) {
         count = this[el].count;
         ind = this[el].ind;
         return;
      };
      if (this[el].count === count && this[el].ind < ind) {
         ind = this[el].ind;
      };
   }, Object.create(null));
   return arr[ind];
};
console.log(getMostFrequentValue(arr));
console.log(getMostFrequentValue(arr1));

Output

And the output in the console will be −

a
a

Updated on: 24-Nov-2020

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements