Skip to content

Instantly share code, notes, and snippets.

@timhettler
Created March 29, 2012 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timhettler/2243300 to your computer and use it in GitHub Desktop.
Save timhettler/2243300 to your computer and use it in GitHub Desktop.
Take a String and return the top N words found within the String, by frequency
(function top(string, num) {
var words = string.toLowerCase().split(/[\s,.]+/),
count = {},
topWords = [];
for(var i=0; i<words.length;i++){
(count[words[i]] !== undefined) ? count[words[i]]++ : count[words[i]] = 1;
}
var list = Object.keys(count).sort(function(a, b){return count[a]-count[b];}).reverse();
for(var i=0; i<num;i++) {
topWords.push(list[i]);
}
return topWords;
})('I scream, you scream, we all scream for ice cream',1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment