Skip to content

Instantly share code, notes, and snippets.

@ricardodsanchez
Created October 2, 2014 14:59
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 ricardodsanchez/f5328ce266f37d35d03b to your computer and use it in GitHub Desktop.
Save ricardodsanchez/f5328ce266f37d35d03b to your computer and use it in GitHub Desktop.
Get frequency of words in a string and return the list of them ordered by most frequent first
function getFrequency(string, cutOff) {
var cleanString = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,""),
words = cleanString.split(' '),
frequencies = {},
word, frequency, i;
for( i=0; i<words.length; i++ ) {
word = words[i];
frequencies[word] = frequencies[word] || 0;
frequencies[word]++;
}
words = Object.keys( frequencies );
return words.sort(function (a,b) { return frequencies[b] -frequencies[a];}).slice(0,cutOff).toString();
}
document.write( getFrequency2( "1 2 1 2 3 1 2 3 1 1 4 test", 3 ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment