Figuring out the highest value through a for in loop - JavaScript


Suppose, we have a comma separator string that contains some fruit names like this −

const str = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grape,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,Grape,Orange,Orange,Apple,Apple,Banana';

We are required to write a JavaScript function that takes in one such string and uses the for in loop to figure out the fruit name that appears for the greatest number of times in the string.

The function should return the fruit string that appears for most number of times.

Example

Following is the code −

const str =
'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grap
e,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,G
rape,Orange,Orange,Apple,Apple,Banana';
const findMostFrequent = str => {
   const strArr = str.split(',');
   const creds = strArr.reduce((acc, val) => {
      if(acc.has(val)){
         acc.set(val, acc.get(val) + 1);
      }else{
         acc.set(val, 1);
      };
      return acc;
   }, new Map());
   return Array.from(creds).sort((a, b) => b[1] - a[1])[0][0];
};
console.log(findMostFrequent(str));

Output

This will produce the following output in console −

Banana

Updated on: 30-Sep-2020

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements