Last active
September 18, 2019 20:42
-
-
Save bradtaniguchi/c1e3108428275f38eb503c73fc72feaa to your computer and use it in GitHub Desktop.
Quick function that returns the character with the highest count from the string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns the character seen the most in the string | |
*/ | |
const getCharacterWithHighestCount = str => | |
Array.from( | |
str | |
.split('') | |
.reduce( | |
(map, char) => | |
map.has(char) | |
// if the map already has the character, we increment how many times we have seen it | |
? map.set(char, map.get(char) + 1) | |
// if it doesn't have it, then we set the default to 1 | |
: map.set(char, 1), | |
new Map() | |
) | |
.entries() | |
// we go over all entires in the map to get the highestCount for each char. | |
).reduce( | |
([highestChar, highestCount], [char, count]) => | |
count > highestCount ? [char, count] : [highestChar, highestCount] | |
// finally we return the character from the highest | |
)[0]; | |
console.log(getCharacterWithHighestCount('hello world')) // l; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment