Skip to content

Instantly share code, notes, and snippets.

Created April 21, 2018 07:17
What would you like to do?
Challenge: analyze a most frequent word program
function getTokens(rawString) {
// NB: `.filter(Boolean)` removes any falsy items from an array
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
//split() splits the paragraph into words using regular expression
function mostFrequentWord(text) {
var words = getTokens(text); //use getTokens to get an array of words from the paragraoh text
var wordFrequencies = {}; //defing an object to save frequency of every word
for (var i = 0; i <= words.length; i++) { //loop to iterate through the array of words
if (words[i] in wordFrequencies) {
wordFrequencies[words[i]]++; //if the current word already exists in the object, increase its frequecy count by 1
else {
wordFrequencies[words[i]]=1; //if the current word doesn't already exists in the object add a new key for that word and set its value to 1
var currentMaxKey = Object.keys(wordFrequencies)[0];
var currentMaxCount = wordFrequencies[currentMaxKey];
for (var word in wordFrequencies) { //loop to ierate through the object and find the valoue with highest frequency
if (wordFrequencies[word] > currentMaxCount) {
currentMaxKey = word;
currentMaxCount = wordFrequencies[word];
return currentMaxKey; //return that highest frequency key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment