Skip to content

Map & Set

The Course
•
20 min study

Choose the question before the container

An array represents an ordered sequence. A Set represents unique values: new Set(["a", "a"]) has one member. Use add, has, delete, and size to manage membership. A Set of objects compares object identity, not matching ids; store ids when that is the rule you care about.

A Map associates keys with values. new Map() creates one; set stores a key/value pair and get reads it. has distinguishes a missing key from a stored undefined value. Both Map and Set preserve insertion order. Updating an existing key does not move it to the end.

Map with a capital M is the keyed collection constructor. It is different from the lowercase array .map() method, which transforms array items. A Set can be converted to an array with [...ids], yielding its values in insertion order.

For a small UI, an array plus some is often clear enough. Use a Set when you repeatedly need membership, or a Map when you repeatedly need a record by id. The important decision is not which syntax looks advanced: it is what duplicates mean. Here a repeated id replaces the previous record's value but keeps the first key position.

Map and Set are not directly represented as keyed collections by JSON.stringify. Convert to a deliberate array representation before saving data; the final app keeps an array of selected books in memory. The optional storage extension serializes that array explicitly; selecting a book does not persist it across a reload.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
const seen = new Set(["js", "web", "js"]);

console.log(seen.size);
console.log(seen.has("web"));

const byId = new Map();

byId.set("js", { title: "Old" });
byId.set("js", { title: "Revised" });
console.log(byId.size);
console.log(byId.get("js").title);
Check your prediction
Text
2
true
1
Revised

new constructs a collection. The second set replaces the value for js, rather than adding a second js entry.

Choose membership or lookup deliberately

A Set answers whether a value is present. A Map associates a key with another value. Both use identity for object keys, so two separately created records with equal-looking fields are not automatically the same member. For domain identity, store the stable id rather than the entire record.

Map.get alone cannot distinguish a missing key from an explicitly stored undefined. Use has when that difference matters. Think about the question the collection must answer before replacing a simple array with another structure.

Choose membership or lookup deliberately: trace JavaScript
const records = new Set([{ id: "a" }, { id: "a" }]);
const ids = new Set(["a", "a"]);

console.log(records.size);
console.log(ids.size);
Check your prediction
Text
2
1

The record objects have different identities; the string ids are equal values. Deduplicating records by object identity would not enforce unique domain ids.

Choose membership or lookup deliberately: contrast JavaScript
const values = new Map();

values.set("known", undefined);
console.log(values.get("known"));
console.log(values.get("missing"));
console.log(values.has("known"), values.has("missing"));
Check your prediction
Text
undefined
undefined
true false

The lookups look alike, but membership differs. Choose whether undefined is permitted data before deciding that a missing get result is a failure.

Try the rule on new inputs

Try updating an existing key and inspect size and iteration order. Then implement duplicate-id detection with a Set containing string ids. The runtime collection does not choose a domain identity policy for you.

Debug a plausible mistake

Exercise

Repair first-seen uniqueness

Normalize surrounding spaces before removing duplicates. Print Java,Tests for the supplied labels. Keep case significant and preserve input order.

Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.

Debugging workspace JavaScript
const labels = [" Java ", "Tests", "Java"];
const unique = [...new Set(labels)].map(label => label.trim());

console.log(unique.join(","));
Hint 1: the idea

Membership uses the values supplied to the set, not their future display spelling.

Hint 2: a first step

Normalize first, then construct the set.

Show one solution
JavaScript
const labels = [" Java ", "Tests", "Java"];
const normalized = labels.map(label => label.trim());
const unique = [...new Set(normalized)];

console.log(unique.join(","));
Text
Java,Tests

The original printed Java,Tests,Java. The Set compared " Java " with "Java" before trimming, saw two different strings and kept both; trimming afterwards only made the duplicate visible. Trimming first means the Set compares the values you actually mean to deduplicate, and [...new Set(...)] still keeps the first-seen order. A test that only used already-clean labels could not tell the two versions apart.

Build it yourself

Exercise

Minutes per book with a Map

Write minutesByBook(books, sessions). Each session names a bookId. Return { totals, unknown }: totals is a Map from each book's id to { title, minutes }, in the books' order, with every book present even if it has no sessions; unknown counts sessions whose id matches no book. Do not add fields to the book records you were given. Print:

Text
Notes: 45
The Web: 10
unknown sessions: 1
book records untouched: true
Your working space JavaScript
function minutesByBook(books, sessions) {
  // Build a Map from id to { title, minutes }, then add each session.
  return { totals: new Map(), unknown: 0 };
}

const books = [
  { id: "js", title: "Notes" },
  { id: "web", title: "The Web" }
];
const sessions = [
  { bookId: "web", minutes: 10 },
  { bookId: "js", minutes: 20 },
  { bookId: "css", minutes: 15 },
  { bookId: "js", minutes: 25 }
];

const { totals, unknown } = minutesByBook(books, sessions);

for (const { title, minutes } of totals.values()) {
  console.log(`${title}: ${minutes}`);
}
console.log(`unknown sessions: ${unknown}`);
console.log(`book records untouched: ${!("minutes" in books[0])}`);
Hint 1: the idea

Looking a book up by id for every session is exactly what a Map is for: build it once from the books, then each session is one get. A get that returns undefined is how you recognise an unknown id, because every stored value here is an object.

Hint 2: a first step

First fill the Map: loop over books and set each id to a new object { title: book.title, minutes: 0 }. Run it: both titles print with 0 minutes, and the books still have no minutes field because you stored new objects, not the books themselves.

Show one solution
JavaScript
function minutesByBook(books, sessions) {
  const totals = new Map();

  for (const book of books) {
    totals.set(book.id, { title: book.title, minutes: 0 });
  }

  let unknown = 0;

  for (const session of sessions) {
    const entry = totals.get(session.bookId);

    if (entry === undefined) {
      unknown += 1;
      continue;
    }

    entry.minutes += session.minutes;
  }

  return { totals, unknown };
}

const books = [
  { id: "js", title: "Notes" },
  { id: "web", title: "The Web" }
];
const sessions = [
  { bookId: "web", minutes: 10 },
  { bookId: "js", minutes: 20 },
  { bookId: "css", minutes: 15 },
  { bookId: "js", minutes: 25 }
];

const { totals, unknown } = minutesByBook(books, sessions);

for (const { title, minutes } of totals.values()) {
  console.log(`${title}: ${minutes}`);
}
console.log(`unknown sessions: ${unknown}`);
console.log(`book records untouched: ${!("minutes" in books[0])}`);
Text
Notes: 45
The Web: 10
unknown sessions: 1
book records untouched: true

Filling the Map from books first gives every book an entry, so "The Web" appears even before its session is read, and totals.values() follows the books' insertion order rather than the order sessions arrived. Each lookup is one get instead of a find over the whole list. The stored values are new objects, so entry.minutes += ... changes the report, not the caller's records; storing book itself would have added minutes to it. Because every stored value is an object, get returning undefined reliably means "no such id"; with values that could themselves be undefined, you would check totals.has(id) instead.

Explain before moving on

When would an array remain the clearest choice? Why does get alone not distinguish every missing-key case?

Was this article helpful?

Your response is saved on this device.