JavaScript judges the most frequent character in the string and counts the number of times

Time:2021-1-23

requirement:

Output the character with the most times of occurrence in a given string, and count its times.

Realization idea:

  1. utilizecharA()Traverse the string
  2. Store each character to the object. If the object does not have this attribute, the amplitude will be 1. If it exists, it will be + 1
  3. Traverse the object to get the maximum value and the character
  4. In the process of traversal, each character in the string is stored in the object as the attribute of the object, and the corresponding attribute value is the number of times the character appears

Code implementation:

//1. Statistics times
var str = 'abdgdbcaethbganmugthaesqszaphfdvwd';
var obj = {};
//An empty object is created to store each character in the string. Attribute: each character, attribute value: the number of times the character appears
for (var i = 0; i < str.length; i++) {
    //Traversal string
    var chars = str.charAt(i);
    //Chars represents each character of the string
    if (obj[chars]) {
        obj[chars]++;
    } else {
        obj[chars] = 1;
    }
    //Obj [chars] attribute value: the number of times the character appears
    //If it already exists, then the number of times is + 1; otherwise, it is assigned to 1
}
console.log(obj);
//The output object obj displays the number of times each character appears

//2. Traverse the object to find the maximum number of times
var max = 0;
var ch = '';
for (var k in obj) {
    if (obj[k] > max) {
        max = obj[k];
        ch = k;
    }
}
//K for attributes: each character
//Obj [k] represents the attribute value: the number of times the character appears
//Assign the most frequent character to Ch

console.log ('the most characters are '+ CH +' and the times are '+ Max');

Output results:

{a: 5, b: 3, d: 4, g: 3, c: 1, …}
The most character is a, the number of times is 5