查找数组中出现次数第二多的元素 JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/25 6:36:17
我们需要编写一个 JavaScript 函数,该函数接受一个字符串并返回该字符串中出现次数第二多的字符。
示例
其代码为 −
const arr = [5, 2, 6, 7, 54, 3, 2, 2, 5, 6, 7, 5, 3, 5, 3, 4];
const secondMostFrequent = arr => {
const map = arr.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(arr));
输出
控制台中的输出 −
2
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

