Lesson 2 of 8
Counting occurrences
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
How many times each value appears
Explanation
“How many orders are in each status?” and “Which word comes up most often?” are the same kind of question, and you answer both by counting how many times each value appears.
A Map fits better here than a plain object, because it accepts keys of any type and inherits nothing from Object.prototype, so a word like constructor can't break it.
The pattern never changes: map.set(k, (map.get(k) ?? 0) + 1).
Your task
Write countBy(arr) to return a Map with the number of times each value appears, and topOne(arr) to return the most frequent value.
Checks
6 checks- countBy returns a Map
- The counts are correct
- An empty array returns an empty Map
- A key like constructor doesn't break the count
- topOne returns the most frequent value
- topOne works with numbers too