Skip to content

Instantly share code, notes, and snippets.

@bradtaniguchi
Last active September 18, 2019 20:42
Show Gist options
  • Save bradtaniguchi/c1e3108428275f38eb503c73fc72feaa to your computer and use it in GitHub Desktop.
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.
/**
* 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