Lesson 4 of 8
Grouping with reduce
- 15 min
- 5 checks
- 3 hints
- Go to task
Goal
From one list to groups
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.
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- Three sections, one per city
- The city names are correct
- Five names are shown
- Riyadh has two students
- Dammam has one student