Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get all maximum frequency characters in string?

I have a string and I want to retrieve all the characters with maximum occurring frequency. I have created a function that returns a single maximum frequency character in the string. But how to modify it in such a way that it returns all the characters with maximum occurring frequency in form or array or string.

  const str = "helloo"

    function findMaxChar(str) {
        let obj = {}
        let maxVal = 1
        let val 

        for (let i = 0; i < str.length; i++) {
            if (str[i] !== ' ') {
                if (obj.hasOwnProperty(str[i])) {
                    obj[str[i]] = obj[str[i]] + 1
                }
                else {
                    obj[str[i]] = 1
                }
            }}
        for (const item in obj) {
            if (obj[item] > maxVal) {
                maxVal = obj[item]
                val = item
            }
        }
        return val
    }

Desired output = [l, o]   // since both l and o has maximum occuring frequency

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe create a loop that finds the highest number of occurrences in a string, and then in the next loop check what characters appear that many times.

const str = "helloo"

    function findMaxChar(str) {
        let obj = {}
        let maxVal = 0
        let valArr = [];

        for (let i = 0; i < str.length; i++) {
            if (str[i] !== ' ') {
                if (obj.hasOwnProperty(str[i])) {
                    obj[str[i]] = obj[str[i]] + 1
                }
                else {
                    obj[str[i]] = 1
                }
            }}
         
        for (const item in obj) {
            if (obj[item] >= maxVal) {
                maxVal = obj[item];
            }
        }
           
        for (const item in obj) {
            if (obj[item] === maxVal) {
                valArr.push(item)
            }
        }
        
        
         return valArr.length > 1 ? valArr : valArr.join();
        
    }
    
    console.log(findMaxChar(str))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading