Ticket code counts
A support queue exports its category codes on one line. Count every code and print each distinct code alphabetically followed by its number of occurrences.
Input
One line containing 1 to 100 lowercase codes separated by single spaces.
Output
One line per distinct code in alphabetical order: code, one space, count.
Example 1
Input
late damaged late billing damaged late
Output
billing 1 damaged 2 late 3
Counts are collected before the code names are sorted.
Constraints
- Each code contains 1 to 20 lowercase letters
- At least one code is present
Hints
Hint 1 of 3
Use each code as an object key.
Hint 2 of 3
A missing property can fall back with ?? 0.
Hint 3 of 3
Sort Object.keys(counts) before output.
Solution
Show a reference solution and explanation
const codes = readline().split(' ');
const counts = {};
for (const code of codes) counts[code] = (counts[code] ?? 0) + 1;
for (const code of Object.keys(counts).sort()) console.log(code, counts[code]);
Why it works
The object associates each code with a running total. Nullish coalescing supplies the first zero safely, and sorting the keys after counting guarantees deterministic output.
Lesson for this exercise: JavaScript Objects: Properties, Methods and Nesting