Lesson 4 of 8

Grouping with reduce

Goal

From one list to groups

01

Explanation

The reduce method boils a whole array down to a single value, and that value can be an object, which is what makes it good for grouping.

You start with an empty object, and on each pass you put the element under its key:

items.reduce((acc, x) => { (acc[x.cat] ??= []).push(x); return acc }, {})

The ??= operator means "create it if it isn't there yet", and the result is an object whose keys are the group names and whose values are arrays.

02

Your task

Group the students by city, and for each city show a section holding an h3 heading with a list of its students' names under it.

Checks

5 checks
  1. Three sections, one per city
  2. The city names are correct
  3. Five names are shown
  4. Riyadh has two students
  5. Dammam has one student
03

Hints

0/3
index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.