Skip to content

Instantly share code, notes, and snippets.

@CodeSigils
Last active April 3, 2018 08:26
Show Gist options
  • Save CodeSigils/63abacfabd652c910b7d74e14dadbb87 to your computer and use it in GitHub Desktop.
Save CodeSigils/63abacfabd652c910b7d74e14dadbb87 to your computer and use it in GitHub Desktop.
Object Drills
// ========= Most frequent word ========= //
/* In this drill, you need to implement a function named mostFrequentWord.
This function takes a single argument, words. Words is an array of lowercase strings,
with punctuation stripped out.
*/
function mostFrequentWord(words) {
// `words` is an array of strings.
// Create an empty object to hold most frequent words.
var wordsObj = {};
// loop through array indexes
for (var i; i <= words.length; i++) {
// if is in obj, loop incrementing by 1, else assign 1
if (words[i] in wordsObj) {
wordsObj[words[i]]++;
} else {
wordsObj[words[i]] = 1;
}
}
// Return an array. Get first value of first property
var maxKey = Object.keys(wordsObj)[0];
var maxCount = wordsObj[maxKey];
for (var word in wordsObj) {
if (wordsObj[word] > maxCount) {
maxKey = word;
maxCount = wordsObj[word];
}
}
return maxKey;
}
// returns an alphabetically sorted list of words, removing punctuation
// characters
function getTokens(rawString) {
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment