Search code examples
javascriptarraysfor-loopobjectfor-in-loop

I'm really stuck on this recursive function question, I need to return the vowel with the greatest count in an object


const VOWELS = ['a', 'e', 'i', 'o', 'u'];

const mostFrequentVowel = function (words, counter = {}) {
    let count = 0
    if (words.length === 0) {
        return ''
    }
    let lastString = words[words.length - 1]
    for (let i = 0; i < lastString.length; i++) {
        const letter = lastString[i];
        if (VOWELS.includes(letter)) {
            count++
            if (letter in counter) {
                counter[letter] += 1
            } else {
                counter[letter] = 1
            }
        }
    }
    let values = Object.values(counter)
    let max = Math.max(...values)
    for (let vowel in counter) {
        if (counter[vowel] === max) {
            return vowel
        }
    }
    return mostFrequentVowel(words.slice(0, words.length - 1), counter)

}
console.log(mostFrequentVowel(['dog', 'cow', 'pig', 'chicken', 'horse'])); // 'o'
mostFrequentVowel(['dog', 'cow', 'pig', 'chicken']); // 'i' or 'o'

I'm having trouble updating the counter object to reflect the largest vowel. I'm wondering if it's more of an issue with the for in loop near the end or if its some logic in the first for loop.


Solution

  • the problem is that the the first return should be called only if words length === 1 (last word remaining in list). The way the code was written, whenever there is a vowel the first return is called. This if statement can fix this:

    const mostFrequentVowel = function (words, counter = {}) {
        let count = 0
        if (words.length === 0) {
            return ''
        }
        let lastString = words[words.length - 1]
        for (let i = 0; i < lastString.length; i++) {
            const letter = lastString[i];
            if (VOWELS.includes(letter)) {
                count++
                if (letter in counter) {
                    counter[letter] += 1
                } else {
                    counter[letter] = 1
                }
            }
        }
    
        if (words.length === 1) {
            let values = Object.values(counter)
            let max = Math.max(...values)
            for (let vowel in counter) {
                if (counter[vowel] === max) {
                    return vowel
                }
            }
        }
        else {
            return mostFrequentVowel(words.slice(0, words.length - 1), counter);
        };
    };
    

    Hope this answer helps your problem