CodeMIRAI
0 XP

Map and Set

2 min read 6 runnable examples Quiz included

Set: unique values

JavaScript
const tags = new Set(["js", "web", "js", "react", "web"]);
console.log(tags);
console.log(tags.size);
console.log(tags.has("react"));

tags.add("css");
tags.delete("web");
console.log([...tags]);

The fastest way to remove duplicates from an array:

JavaScript
const visits = ["home", "blog", "home", "about", "blog"];
const unique = [...new Set(visits)];
console.log(unique);

Set operations

JavaScript
const a = new Set(["Asha", "Leo", "Mei"]);
const b = new Set(["Leo", "Raj"]);

const union = new Set([...a, ...b]);
const both = [...a].filter((x) => b.has(x));
const onlyA = [...a].filter((x) => !b.has(x));
console.log([...union], both, onlyA);

Map: key-value pairs

A Map is like an object, but its keys can be any type (numbers, objects, even functions), it remembers insertion order, and it has a size:

JavaScript
const prices = new Map();
prices.set("tea", 20);
prices.set("coffee", 35);
prices.set(42, "the answer");        // a number key

console.log(prices.get("coffee"));
console.log(prices.has("juice"));
console.log(prices.size);

for (const [item, price] of prices) {
  console.log(item, "→", price);
}

Counting with a Map

JavaScript
const words = "the cat and the hat and the bat".split(" ");
const counts = new Map();
for (const w of words) {
  counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(counts);
console.log([...counts].sort((a, b) => b[1] - a[1])[0]);

Objects as keys

JavaScript
const asha = { name: "Asha" };
const leo = { name: "Leo" };

const lastSeen = new Map();
lastSeen.set(asha, "today");
lastSeen.set(leo, "yesterday");
console.log(lastSeen.get(asha));

A plain object would turn both keys into the string "[object Object]", so they'd collide.

Which one should I use?

NeedUse
ordered list, duplicates allowedArray
unique values, fast "is it there?"Set
fixed record with known fields (user.name)Object
lookup table with dynamic or non-string keysMap
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.