在 JavaScript 中查找第二常见的字符

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/1 0:44: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

相关文章


有用资源