Search code examples
javascriptobjectlogicjavascript-objectsfor-in-loop

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

  • 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))