Finding Most-Used Words (Mini Linter Step 8, Option 2)


#1

I’d love to see examples of how other people are finding the most-used word (the second of the three suggestions for extending the linter in Step 8).

Write a function that finds the word that appears the greatest number of times.

Mine works but I’m sure there are better ways

/**
 * Attempt to find the most common words in the paragraph
 */

// betterWords is an array of all words remaining in Step 7
let cleanList = betterWords.map( function( word ) {
 	word = word.toLowerCase();
  
  // these would be better as a RegEx
  word = word.replace('.','');
  word = word.replace('!','');
  word = word.replace(',','');
  word = word.replace('"','')
  
  return word;
});

// alphabetize so words are grouped consecutively
let alphaList = cleanList.sort();

// will start loop on 2nd word and compare to 1st
let maxWord = alphaList[0],
		maxWordCount = 1,
		newWord = '',
    lastWord = alphaList[0],
    currentWordCount = 1;

for ( i = 1; i < alphaList.length; i++ ) {
  
  // get the next word
  newWord = alphaList[i];
  
  // if this is same as last word, add to count. Restart otherwise.
  if( lastWord === newWord ) {
    currentWordCount++;
  } else {
    currentWordCount = 1;
  }
  
  // if this words is more than our maxWord, update word and count
  if( currentWordCount > maxWordCount ) {
    maxWordCount = currentWordCount;
    maxWord = lastWord;
  }
  
  // set last word for next iteration of loop
  lastWord = newWord;
  
}

console.log( `Your most-used word is "${maxWord}" which you used ${maxWordCount} times.`);

The result:

Your most-used word is “the” which you used 14 times.