How to get the most common values in array: JavaScript ?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals that have repeating values. Our function should return an array of the most common element(s) in the array (if two or more elements appear for the same number of most times then the array should contain all those elements).

Example

The code for this will be −

const arr1 = ["a", "c", "a", "b", "d", "e", "f"];
const arr2 = ["a", "c", "a", "c", "d", "e", "f"];
const getMostCommon = arr => {
   const count = {};
   let res = [];
   arr.forEach(el => {
      count[el] = (count[el] || 0) + 1;
   });
   res = Object.keys(count).reduce((acc, val, ind) => {
      if (!ind || count[val] > count[acc[0]]) {
         return [val];
      };
      if (count[val] === count[acc[0]]) {
         acc.push(val);
      };
      return acc;
   }, []);
   return res;
}
console.log(getMostCommon(arr1));
console.log(getMostCommon(arr2));

Output

And the output in the console will be −

[ 'a' ]
[ 'a', 'c' ]
raja
Published on 21-Nov-2020 09:34:41
Advertisements