Home > Software design >  How to get all maximum frequency characters in string?
How to get all maximum frequency characters in string?

Time:01-21

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

CodePudding user response:

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

CodePudding user response:

Sounds pretty straight forward, find the maximum frequency and then all chars that occurred with this frequency:

const maxFrequence = Math.max(...Object.values(obj))
const elements = Object.keys(obj).filter( char => obj[char] === maxFrequency)
  • Related