Created
March 29, 2012 20:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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