Lesson 2 of 8

Counting occurrences

Goal

How many times each value appears

01

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).

02

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
  1. countBy returns a Map
  2. The counts are correct
  3. An empty array returns an empty Map
  4. A key like constructor doesn't break the count
  5. topOne returns the most frequent value
  6. topOne works with numbers too
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.