Read the question, write JavaScript on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read one line of words. Log each distinct word and how many times it appears, one per line, sorted alphabetically.
Each line is the word, a space, then the count. An object makes a natural tally.
Input. One line of space-separated words.
Output. Lines of "word count", sorted alphabetically by word.
Examples
Input
the cat the dog the
Output
cat 1 dog 1 the 3
Hint
- counts[w] = (counts[w] || 0) + 1 handles the "first time seen" case in one line.
- Object.keys(counts).sort() gives the words in alphabetical order.
Show correct code
Peek only after you have tried. You can still Check your own version.
const words = readLine().trim().split(/\s+/).filter(Boolean);
const counts = {};
for (const w of words) counts[w] = (counts[w] || 0) + 1;
for (const key of Object.keys(counts).sort()) console.log(`${key} ${counts[key]}`);
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.