Skip to content

Instantly share code, notes, and snippets.

@w3cj
Last active December 1, 2015 20:51
Show Gist options
  • Select an option

  • Save w3cj/2c1f552f29b488886a09 to your computer and use it in GitHub Desktop.

Select an option

Save w3cj/2c1f552f29b488886a09 to your computer and use it in GitHub Desktop.
function countLetters(input) {
// a place to store the counters
var counters = {};
// get the length of the input string
input = input.toLowerCase();
// iterate over the chars of the string
for (var i = 0; i < input.length; i++) {
// check to see if a letter
if(input[i] <= 'z' && input[i] >= 'a') {
// convert the char to lowercase - str.toLowerCase();
if(counters.hasOwnProperty(input[i])) {
// increment counter for given char obj[char]++
counters[input[i]]++;
}
else {
counters[input[i]] = 1;
}
}
}
// print out the char counts
console.log(JSON.stringify(counters));
}
countLetters("The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment