DEV Community

Discussion on: Javascript Algorithms Challenges | Part 2

Collapse
 
patriklarsson profile image
Patrik • Edited

Love this article and it's a great primer for someone to start solving these problems.

Just because I love to see iterative improvements, can I suggest you move the check for maxChar into your first loop to avoid the second. With a reduce you could instead do:

function maxCharacter(str) {
    var maxNum = 0,
        maxChar;

    str.split('').reduce((letters, letter) => {
        if (!letters[letter]) {
            letters[letter] = 0;
        }
        letters[letter]++;

        if (letters[letter] > maxNum) {
        maxChar = letter;
            maxNum = letters[letter];
        }

        return letters;
    }, []);

    return maxChar;
}
Collapse
 
martinnrdstrm profile image
Martin Nordström

Thanks for your suggestion Patrick!

Smart move with using the reduce method and moving the check!