freeCodeCamp Challenge Guide: Word frequency

Word frequency


Solutions

Solution 1 (Click to Show/Hide)
function wordFrequency(txt, n) {
  var words = txt.split(/\s+/);
  var wordCount = {};
  words.forEach(word => {
    if (word == '') {
      return;
    }
    const lowerWord = word.toLowerCase();
    wordCount[lowerWord] =
      lowerWord in wordCount ? wordCount[lowerWord] + 1 : 1;
  });
  var wordsArray = [];
  for (let [word, count] of Object.entries(wordCount)) {
    wordsArray.push([word, count]);
  }
  wordsArray.sort((a, b) => {
    if (a[1] !== b[1]) {
      return b[1] - a[1];
    } else if (a[0] !== b[0]) {
      return a[0] < b[0] ? -1 : 1;
    }
    return 0;
  });
  return wordsArray.slice(0, n);
}
Solution 2 (Click to Show/Hide)
function wordFrequency(txt, n) {
  // Convert input to array of words
  const words = txt == ""
    ? []
    : txt.trim()
      .split(/\s+/)
      .map(word => word.toLowerCase());
  // Count unique words
  const wordCounts = {};
  words.forEach(word => {
    // Create hashmap entry if not found yet
    if (!wordCounts[word]) {
      wordCounts[word] = [word, 0];
    }
    // Increment hashmap count
    wordCounts[word][1]++;
  });
  // Convert hashmap to array, sort, and slice
  return Object.values(wordCounts)
    .sort((a, b) => b[1] != a[1]
      ? b[1] - a[1]
      : b[0] > a[0] ? -1 : 1
    ).slice(0, n);
}
1 Like