从字符串(包括空格)返回第二高频率字符-JavaScript

我们需要编写一个JavaScript函数,该函数接受一个字符串并返回在字符串中出现第二多的字符。

示例

以下是代码-

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));

输出结果

以下是控制台中的输出-

e