Returning the second most frequent character from a string (including spaces) - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string and returns the character which makes second most appearances in the string.

Example

Following is the code −

const str = 'Hello world, I have never seen such a beautiful weather in
the world';
const secondFrequent = str => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      map[str[i]] = (map[str[i]] || 0) + 1;
   };
   const freqArr = Object.keys(map).map(el => [el, map[el]]);
   freqArr.sort((a, b) => b[1] - a[1]);
   return freqArr[1][0];
};
console.log(secondFrequent(str));

Output

Following is the output in the console −

e
raja
Published on 18-Sep-2020 09:13:24
Advertisements