Calculate the number of occurrences of each character and which character appears the most, taking into account the situation that multiple characters have the same number of occurrences

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Calculate the number of occurrences of each character and which character appears most</title>

</head>

<body>

   

</body>

<script type="text/javascript">

//Calculate the number of occurrences of each character and which character appears most

let str = 'gggjjggyyyooppoooww';

function findString(str){

    let StringNum = {};

//Traverse the string to get the object {character: number of occurrences}

    for(let i=0;i < str.length;i++){

        let e = str.charAt(i);

        if(StringNum[e]){

            StringNum[e]++;

        }else{

            StringNum[e] = 1;

        }

    }

    console.log(StringNum);

    let {maxArr,count} = {maxArr:[],count:0};

//Loop through the object to find the element with the most occurrences

    for (let key in StringNum) {

//If there are more occurrences, you need to remove the previous element and add the current element

        if (count < StringNum[key]) {

            count = StringNum[key];

            maxArr.shift();

            maxArr.push(key);

        }

//The number of occurrences is the same, add elements to the array

        if (count == StringNum[key] && maxArr.indexOf(key) == -1) {

            maxArr.push(key);

        }

    }

//Return object {array of high-frequency characters, maximum number of occurrences}

    return {maxArr,count}

}

console.log(findString(str));

</script>

</html>

 

 

Guess you like

Origin blog.csdn.net/weixin_46501763/article/details/128152692