返回字符串中出现次数第二多的字符(包括空格) - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/11 14:04:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

