Second most frequent character in a string - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string and returns the character from the string that appears for second most number of times.

Let’s say the following is our string −

const str = 'This string will be used to calculate frequency';

Above, the second most frequent character is “e”.

Example

Let us now see the complete code −

const str = 'This string will be used to calculate frequency';
const secondMostFrequent = str => {
   const strArr = str.split('');
   const map = strArr.reduce((acc, val) => {
      if(acc.has(val)){
         acc.set(val, acc.get(val) + 1);
      }else{
         acc.set(val, 1);
      };
      return acc;
   }, new Map);
   const frequencyArray = Array.from(map);
   return frequencyArray.sort((a, b) => {
      return b[1] - a[1];
   })[1][0];
};
console.log(secondMostFrequent(str));

Output

This will produce the following output in console −

e
raja
Published on 30-Sep-2020 14:11:15
Advertisements