Skip to content

Instantly share code, notes, and snippets.

@rabet
Last active October 13, 2017 19:29
Show Gist options
  • Save rabet/426665b1d6b199a3c88a384fbb2f0ca9 to your computer and use it in GitHub Desktop.
Save rabet/426665b1d6b199a3c88a384fbb2f0ca9 to your computer and use it in GitHub Desktop.
// Count the each letter occurance in the "text",
// the result put into the "stats" object in a form of:
// {
// a: 10,
// c: 13,
// ...
// }
//
// NOTE! count letters only,
// consider lower case and upper case letter to be the same
const text = 'Prince Andrei could not look with indifference at the standards of the battalions going past him. Looking at a standard, he thought: maybe it is that very standard with which I\'ll have to march at the head of the troops.'
// replace all non-alphanumeric characters, then convert all characters to lower-case, because the upper-case will move in front after sort, then split to single chars array
const stats = text.replace(/\W/g, '').toLowerCase().split('')
stats.sort()
// reduce to object with keys as a letter, in every step I check if the key is already in the acc object, and if it is, I increase the count by 1
const reducedStats = stats.reduce((acc, letter) => {
if (letter in acc) {
acc[letter]++
} else {
acc[letter] = 1
}
return acc
}, {})
console.log(reducedStats);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment