Byte's cat show
Set: unique values. Map: key → value pairs with keys of any type.
Set for the first and Map for the second.const guests = new Set();
guests.add("Mittens");
guests.add("Oscar");
guests.add("Mittens");
console.log(guests.size);
console.log(guests.has("Oscar"));
guests.delete("Oscar");
console.log(guests);A `Set` is a collection of unique values. Everything you can do with it:
add(value)— add it (a repeat is simply ignored);has(value)— is it there:trueorfalse;delete(value)— remove it;size— how many values are inside (a property, not a method: no parentheses).
A Set has no indexes: you can't ask "who's third?", only "is this one here?".
const turnstile = ["Mittens", "Fluffy", "Mittens", "Tiger", "Fluffy"];
const unique = [...new Set(turnstile)];
console.log(unique);
for (const name of new Set(turnstile)) {
console.log("Welcome,", name);
}[...new Set(arr)] is the shortest way to drop duplicates. The order is the order of first appearance.const badges = new Set();
badges.add({ name: "Mittens" });
badges.add({ name: "Mittens" });
console.log(badges.size);
const mittens = { name: "Mittens" };
const sameBadges = new Set([mittens, mittens]);
console.log(sameBadges.size);Now the registry. A `Map` stores key → value pairs, like an object, but the key can be anything: a string, a number, even another object. The methods look like Set's:
const registry = new Map();
registry.set("Mittens", "Siamese");
registry.set("Oscar", "Maine Coon");
console.log(registry.get("Mittens"));
console.log(registry.get("Rex"));
console.log(registry.has("Oscar"), registry.size);
const mittens = { name: "Mittens", owner: "Ann" };
const prizes = new Map();
prizes.set(mittens, "best whiskers");
console.log(prizes.get(mittens));undefined. And the prize's key is the cat object itself.The most common trick with a Map is counting. Walk the list and add one to each value's counter. The ?? operator means "if the left side is undefined or null, take the right side": that's how a cat's first vote starts from zero.
And for...of over a Map gives you [key, value] pairs — handy to unpack right away with destructuring.
const votes = ["Mittens", "Tiger", "Mittens", "Fluffy", "Mittens"];
const tally = new Map();
for (const name of votes) {
tally.set(name, (tally.get(name) ?? 0) + 1);
}
for (const [name, count] of tally) {
console.log(name, count);
}Map.const scores = { Mittens: 9, Tiger: 7 };
const map = new Map(Object.entries(scores));
map.set("Fluffy", 8);
console.log(map.size);
console.log(Object.fromEntries(map));Map with Object.entries, and back with Object.fromEntries.Set is the guest list at the door ("been here or not?"), a Map is the registry ("who is this and what do we know?"). Why not just use a plain object? That's the next lesson. Spoiler: you can — until a cat named constructor signs up for the show.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.