Count the most frequently occurring characters and times in a string in JavaScript
Ideas:
- The string should be converted into an array and then deduplicated;
- Second, count the number of occurrences of each letter;
- Compare the character with the most occurrences.
code show as below:
// 统计一个字符,中出现次数最多的字符。
var str = "nfjskdhfjksnumberZZZ"
var number = [];
for(var i = 0;i < str.length;i++){
var char = str.charAt(i);
if(number[char]){
number[char]++;
}else{
number[char] = 1;
}
}
console.log(number);
var max = 0;
var maxnumber = null;
for(var j in number){
if(max < number[j]){
max = number[j];
maxnumber = j;
}
}
console.log("最多的字符为:"+maxnumber);
console.log("出现最多次数为:"+max);
The result of the operation is: