Skip to content

Instantly share code, notes, and snippets.

@sayanriju
Created February 17, 2017 08:45
Show Gist options
  • Save sayanriju/aa145365bcf60f277c6c42198382e107 to your computer and use it in GitHub Desktop.
Save sayanriju/aa145365bcf60f277c6c42198382e107 to your computer and use it in GitHub Desktop.
JS Find Frequency of Letters in a Sentence
String.prototype.countLetterFreq = function () {
return this
.split('')
.filter(l => l.trim())
.map(l => l.toLowerCase())
.reduce( (acc, cur) => { acc[cur] = (acc[cur] === undefined) ? 1 : acc[cur] + 1; return acc; }, {} )
}
// Usage:
// > "This is a nice sentence".countLetterFreq()
// Returns:
// > { t: 2, h: 1, i: 3, s: 3, a: 1, n: 3, c: 2, e: 4 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment