返回数组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