返回数组JavaScript中出现次数第二多的元素
我们需要编写一个包含一组文字的JavaScript函数。该函数应返回在数组中出现次数第二多的元素。
例如-
如果输入数组是-
const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
那么输出应该是-
const output = 2;
示例
const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
const findSecondMost = (arr = []) => {
const map={};
arr.forEach(el => {
if(map.hasOwnProperty(el)){
map[el]++; }else{ map[el] = 1;
}
})
const sorted = Object.keys(map).sort((a,b) => map[b]-map[a]);
return sorted[1];
};
console.log(findSecondMost(arr));输出结果
控制台中的输出将是-
2
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短