字符串中第二常见的字符——JavaScript
我们要编写一个 JavaScript 函数,它接收一个字符串,并返回字符串中出现第二频繁的字符。
假设以下为我们的字符串:
const str = 'This string will be used to calculate frequency';
上面最频繁出现的是“e”。
示例
现在让我们看下完整的代码:
const str = 'This string will be used to calculate frequency';
const secondMostFrequent = str => {
const strArr = str.split('');
const map = strArr.reduce((acc, val) => {
if(acc.has(val)){
acc.set(val, acc.get(val) + 1);
}else{
acc.set(val, 1);
};
return acc;
}, new Map);
const frequencyArray = Array.from(map);
return frequencyArray.sort((a, b) => {
return b[1] - a[1];
})[1][0];
};
console.log(secondMostFrequent(str));输出
以下输出将显示在控制台中:
e
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP