TypeScript bootcamp · Lab 50

Word frequency

mediumMap12 minLesson: Map

Read the question, write TypeScript on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Tally words; print alphabetically.

Examples

Example 1
Input
the cat the dog the
Output
cat 1
dog 1
the 3
Hint
  1. Map or object + sort keys
Show correct code

Peek only after you have tried. You can still Check your own version.

const words: string[] = readLine().trim().split(/\s+/).filter(Boolean);
const counts: Record<string, number> = {};
for (const w of words) counts[w] = (counts[w] || 0) + 1;
for (const k of Object.keys(counts).sort()) console.log(`${k} ${counts[k]}`);
main.tstsc · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.