Four small, realistic uses of Map and Set.
1. Counting how often things appear
const text = "the quick brown fox jumps over the lazy dog the end";
const counts = new Map();
for (const word of text.split(" ")) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
const mostCommon = [...counts].sort((a, b) => b[1] - a[1])[0];
console.log(mostCommon); // → ["the", 3]
2. Grouping items
const products = [
{ name: "Pen", category: "stationery" },
{ name: "Mug", category: "kitchen" },
{ name: "Notebook", category: "stationery" }
];
const byCategory = new Map();
for (const product of products) {
if (!byCategory.has(product.category)) byCategory.set(product.category, []);
byCategory.get(product.category).push(product.name);
}
console.log(byCategory);
// → Map(2) { 'stationery' => ['Pen', 'Notebook'], 'kitchen' => ['Mug'] }
3. Unique values and quick lookups
const emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com"];
const unique = [...new Set(emails)];
console.log(unique.length); // → 3
const blocked = new Set(["c@x.com"]);
console.log(unique.filter(email => !blocked.has(email))); // → ["a@x.com", "b@x.com"]
4. Memoising (caching) a function
function memoize(fn) {
const cache = new Map();
return function (arg) {
if (cache.has(arg)) {
console.log("from cache");
return cache.get(arg);
}
const result = fn(arg);
cache.set(arg, result);
return result;
};
}
const square = memoize(n => n * n);
console.log(square(9)); // → 81
console.log(square(9)); // → 81 (and "from cache" is printed)
5. Tracking selected items on a page
<ul id="list">
<li data-id="1">Apple</li>
<li data-id="2">Banana</li>
<li data-id="3">Cherry</li>
</ul>
<p id="out">Selected: none</p>
<script>
const selected = new Set();
document.querySelector("#list").addEventListener("click", event => {
const li = event.target.closest("li");
if (!li) return;
const id = li.dataset.id;
selected.has(id) ? selected.delete(id) : selected.add(id);
li.style.fontWeight = selected.has(id) ? "bold" : "normal";
document.querySelector("#out").textContent = "Selected: " + ([...selected].join(", ") || "none");
});
</script>
A Set fits perfectly: an item is either selected or not, and there are no duplicates.
Choosing a structure
| Need | Use |
|---|---|
| Ordered list that may repeat | Array |
| Record with known fields | Object |
| Lookup by any key, counting, grouping | Map |
Unique values, fast has | Set |
| Attach data to objects without leaks | WeakMap / WeakSet |