The challenge
Write wordCount(text) that returns an object with each word (in lowercase) and how many times it appears. Words are separated by spaces.
wordCount("the cat and the hat")
// { the: 2, cat: 1, and: 1, hat: 1 }
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
wordCount("the cat and the hat")gives{ the: 2, cat: 1, and: 1, hat: 1 }wordCount("Go go GO")gives{ go: 3 }wordCount("hi")gives{ hi: 1 }
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Start with const counts = {}; and loop over text.toLowerCase().split(" ").
Hint 2
counts[word] = (counts[word] || 0) + 1;
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function wordCount(text) {
const counts = {};
for (const word of text.toLowerCase().split(" ")) {
counts[word] = (counts[word] || 0) + 1;
}
return counts;
}
Learn what you need
This exercise uses what Grade 8: Objects: Describing Things With Labels teaches. Read those notes first if any of it is new.