Choose a Map Over an Object

In the last lesson, you counted the club’s genres into an object with .reduce(). An object can hold a tally, but it was built to describe one thing with named properties, and using it for counts brings a couple of catches.

The report’s next line shows how many books the club read by each author. In this lesson, you’ll count them into a container that stores values by key, read the counts back, and loop over them. You’ll also be able to say when a plain object is still the better choice. Start with the shape of the data, then swap in the new container and keep the tally code you already have.

Swap in a Map for the Tally

The author count covers the whole club, so it works on allBooks, the flat array of every member’s book records. Here’s its shape, with only a few properties shown, and the shape the count should end with:

allBooks: array of 15 book objects
  [0]  { title: "Kindred",     author: "Octavia E. Butler", ... }
  [1]  { title: "The Martian", author: "Andy Weir", ... }
  [2]  { title: "Circe",       author: "Madeline Miller", ... }
  ...
  [14] { title: "Kindred",     author: "Octavia E. Butler", ... }

books per author: one entry per author
  "Octavia E. Butler" → number, "Andy Weir" → number, ...

Each book adds one to its author’s count. An object tally would work for author names, which are strings already, but it has two catches you’ve met. counts[5] = 1 stores the key as the string '5', and "toString" in counts is true before you count anything.

A Map is a built-in object that holds key-value pairs, called entries, and keeps every key as you gave it, so a number stays a number. A new Map starts with no entries.

You create one with new Map(), the way {} creates an empty object. The new keyword builds a fresh object from a constructor such as Map, and that’s all you need about new for now.

A Map counts its own entries in its .size property, which for the report is the number of different authors. Open report.js. Keep the club’s log and the loop that builds allBooks, and delete or comment out the last lesson’s jobs. Then write the author tally the way you wrote the genre tally, swapping only the container, and log the Map too:

Language: JavaScript
const booksPerAuthor = new Map();
for (const book of allBooks) {
  const author = book.author;
  booksPerAuthor[author] = (booksPerAuthor[author] ?? 0) + 1;
}
console.log(booksPerAuthor.size);
console.log(booksPerAuthor);

Your file should now hold the log, allBooks, and the bracket tally:

Language: JavaScript Filename: report.js
const log = [
  {
    name: "Maya",
    books: [
      {
        title: "Kindred",
        author: "Octavia E. Butler",
        genre: "sci-fi",
        rating: 5,
        review: "Couldn't put it down.",
      },
      { title: "The Martian", author: "Andy Weir", genre: "sci-fi", rating: 4 },
      {
        title: "Circe",
        author: "Madeline Miller",
        genre: "fantasy",
        rating: 3,
        review: "Slow start, lovely ending.",
      },
      { title: "Educated", author: "Tara Westover", genre: "memoir", rating: 4 },
    ],
  },
  {
    name: "Jamal",
    books: [
      {
        title: "The Thursday Murder Club",
        author: "Richard Osman",
        genre: "mystery",
        rating: 5,
        review: "Funny and clever.",
      },
      { title: "Born a Crime", author: "Trevor Noah", genre: "memoir", rating: 3 },
      {
        title: "The Man Who Died Twice",
        author: "Richard Osman",
        genre: "mystery",
        rating: 4,
      },
    ],
  },
  {
    name: "Rosa",
    books: [
      {
        title: "Parable of the Sower",
        author: "Octavia E. Butler",
        genre: "sci-fi",
        rating: 5,
        review: "Hard to read, harder to forget.",
      },
      {
        title: "Little Fires Everywhere",
        author: "Celeste Ng",
        genre: "fiction",
        rating: 4,
      },
      {
        title: "Project Hail Mary",
        author: "Andy Weir",
        genre: "sci-fi",
        rating: 5,
      },
    ],
  },
  {
    name: "Dev",
    books: [
      {
        title: "Project Hail Mary",
        author: "Andy Weir",
        genre: "sci-fi",
        rating: 4,
      },
      {
        title: "Circe",
        author: "Madeline Miller",
        genre: "fantasy",
        rating: 0,
        review: "Gave up halfway.",
      },
    ],
  },
  {
    name: "Hannah",
    books: [
      { title: "Educated", author: "Tara Westover", genre: "memoir", rating: 5 },
      { title: "Born a Crime", author: "Trevor Noah", genre: "memoir", rating: 4 },
      { title: "Kindred", author: "Octavia E. Butler", genre: "sci-fi", rating: 4 },
    ],
  },
  { name: "Luis", books: [] },
];

const allBooks = [];
for (const member of log) {
  for (const book of member.books) {
    allBooks.push(book);
  }
}

const booksPerAuthor = new Map();
for (const book of allBooks) {
  const author = book.author;
  booksPerAuthor[author] = (booksPerAuthor[author] ?? 0) + 1;
}
console.log(booksPerAuthor.size);
console.log(booksPerAuthor);

The club’s books have seven different authors. Before you run the script, decide what the size line will print, then run it:

The size comes out as 0, but the counts are there:

Language: Shell
$ node report.js
0
Map(0) {
  'Octavia E. Butler': 3,
  'Andy Weir': 3,
  'Madeline Miller': 2,
  'Tara Westover': 2,
  'Richard Osman': 2,
  'Trevor Noah': 2,
  'Celeste Ng': 1
}

Map(0) means zero entries, and each item after it with a colon, such as 'Andy Weir': 3, is an ordinary property. A Map is an object too, so brackets read and set properties on it, as they do on any object.

Your counts landed on the Map object itself, outside its entries, where .size never looks. A Map still inherits methods such as toString as properties, but entries are kept apart from properties, so the Map’s lookups never see them.

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.