字符串中第二常见的字符-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
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法