记录字符串出现最多次数

标签: javascipt


直接放代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var x = "hiohadlkioyiyimfia";
function count(str){
var obj = {};
for(var i=0;i<str.length;i++){
if(!obj[str.charAt(i)]){
obj[str.charAt(i)] = 1;
}else{
obj[str.charAt(i)]++;
}
}
return Object.entries(obj).map(i=>i[1]).sort((a, b) => b - a)[0];
// return Object.entries(obj).map(i=>i[1]).reduce((a,b)=>a > b ? a : b);
}
console.log(count(x));

全部修改为箭头函数

1
2
3
4
5
6
const count=(str)=> {
let obj=str.split('').reduce((m, n) => (m[n]++ || (m[n] = 1), m), {})
return Object.entries(obj).map(i=>i[1]).reduce((a,b)=>a > b ? a : b);
};
var x = "ayeiorewoajupoao";
console.log(count(x));