Back to Freecodecamp

Challenge 35: Word Frequency

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf227324381476f.md

latest1.8 KB
Original Source

--description--

Given a paragraph, return an array of the three most frequently occurring words.

  • Words in the paragraph will be separated by spaces.
  • Ignore case in the given paragraph. For example, treat Hello and hello as the same word.
  • Ignore punctuation in the given paragraph. Punctuation consists of commas (,), periods (.), and exclamation points (!).
  • The returned array should have all lowercase words.
  • The returned array should be in descending order with the most frequently occurring word first.

--hints--

getWords("Coding in Python is fun because coding Python allows for coding in Python easily while coding") should return ["coding", "python", "in"].

js
assert.deepEqual(getWords("Coding in Python is fun because coding Python allows for coding in Python easily while coding"), ["coding", "python", "in"]);

getWords("I like coding. I like testing. I love debugging!") should return ["i", "like", "coding"].

js
assert.deepEqual(getWords("I like coding. I like testing. I love debugging!"), ["i", "like", "coding"]);

getWords("Debug, test, deploy. Debug, debug, test, deploy. Debug, test, test, deploy!") should return ["debug", "test", "deploy"].

js
assert.deepEqual(getWords("Debug, test, deploy. Debug, debug, test, deploy. Debug, test, test, deploy!"), ["debug", "test", "deploy"]);

--seed--

--seed-contents--

js
function getWords(paragraph) {

  return paragraph;
}

--solutions--

js
function getWords(paragraph) {
  const cleaned = paragraph.replace(/[.,!]/g, "").toLowerCase();
  const words = cleaned.split(/\s+/);

  const freq = {};
  for (const word of words) {
    if (word) {
      freq[word] = (freq[word] || 0) + 1;
    }
  }

  const sorted = Object.keys(freq).sort((a, b) => freq[b] - freq[a]);
  return sorted.slice(0, 3);
}