在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