Group Records by a Key

So far, you’ve counted the club’s books by genre and by author and kept each author once in a Set. A count tells you the club read six sci-fi books, but not which six. A year-end report could give each genre a page listing its books, and that page would need the books themselves, grouped by genre.

In this lesson, you’ll group allBooks by genre with a loop, with .reduce(), and with a built-in function made for the job, and you’ll be able to describe the shape each approach produces. Start by sketching what goes in and what should come out.

Group Books With a Loop

A genre page needs every book of one genre in one place, but allBooks has them scattered among the other genres. Here’s the shape that goes in, showing only the properties this lesson reads, and the shape that should come out:

allBooks: array of 15 book objects
  [0]  { title: "Kindred",     genre: "sci-fi",  ... }
  [1]  { title: "The Martian", genre: "sci-fi",  ... }
  [2]  { title: "Circe",       genre: "fantasy", ... }
  ...
  [14] { title: "Kindred",     genre: "sci-fi",  ... }

books by genre: object, one key per genre
  "sci-fi": array of book objects
  fantasy:  array of book objects
  ...

The result is an object of arrays: a genre key leads to a list of book records, each a plain object. Each list is a group, the records that share one value for a key. You build nested data from a flat list, the reverse of building allBooks from the log.

The loop looks like your genre tally, with one change. A tally adds one to a number, but a grouping loop pushes the book onto an array with .push(), and that array has to exist before the first push. Open report.js, keep the log and the loop that builds allBooks, and delete the Set work from before. Then add the grouping loop:

Language: JavaScript
const byGenre = {};
for (const book of allBooks) {
  if (!Object.hasOwn(byGenre, book.genre)) {
    byGenre[book.genre] = [];
  }
  byGenre[book.genre].push(book);
}

The if asks whether this genre has a key yet. For the first sci-fi book, it doesn’t, so the loop starts an empty array under "sci-fi". For every later sci-fi book, the key is there, so the loop skips the if block and pushes onto the array that’s already waiting.

Watch out: without the if, the line byGenre[book.genre] = []; runs for every book and replaces the genre’s array each time, so every genre ends up holding only its last book.

Starting each group only once is the step that’s easiest to get wrong. The mentor can trace the loop with you, one book at a time:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.