Find the most frequently occurring character and number of times in a string

Count the most frequently occurring characters and times in a string in JavaScript

Ideas:

  1. The string should be converted into an array and then deduplicated;
  2. Second, count the number of occurrences of each letter;
  3. 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:

Guess you like

Origin blog.csdn.net/Z_CH8648/article/details/127720578