笔试题:出现最多的字符以及出现的次数
问题描述:
找出这个数组中出现次数最多的一项及这一项出现了多少次
const arr = [1, 2, 1, 2, '1', '1', '2', '2', 1, '2', '2', 4, 5, 6 ]
let map=new Map();
// 注意判断map结构的时候,先使用has()来判断键是否存在于map中
let obj=arr.reduce((pre,cur)=>{
if(pre.has(cur)){
let temp=pre.get(cur)+1;
pre.set(cur,temp);
}else{
pre.set(cur,1);
}
return pre;
},map);
let max= Math.max(...obj.values());
for(let item of obj.keys()){
if(obj.get(item)===max){
console.log(typeof item,max);
}
console.log(item)
}