Maps and Sets
Overview
Objects and arrays cover most needs, but two built-in collections solve common problems more cleanly:
- A
Setis a collection of unique values. Add the same value twice and it’s stored once. - A
Mapis a collection of key–value pairs, like an object, but its keys can be anything — numbers, objects, functions, DOM elements.
Set — unique values
const tags = new Set(['web', 'js', 'web']);
tags.size; // 2
tags.has('js'); // true
tags.add('css'); // returns the set, so calls can be chained
tags.delete('web'); // true if it was there
tags.clear(); // removes everything
for (const tag of tags) console.log(tag);Removing duplicates from an array is a one-liner:
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]Why use a Set?
set.has(x) is very fast however many items there are, whereas array.includes(x) checks items one by one. When you check membership often — “has this user already voted?”, “have we seen this URL?” — a Set is the right tool:
const seen = new Set();
for (const url of urls) {
if (seen.has(url)) continue; // skip repeats
seen.add(url);
crawl(url);
}Set operations
Modern browsers include methods for combining sets:
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
a.union(b); // Set {1, 2, 3, 4}
a.intersection(b); // Set {2, 3}
a.difference(b); // Set {1}
a.isSubsetOf(b); // falseIn older environments you can do the same with spread and filter: new Set([...a].filter((x) => b.has(x))) is the intersection.
Map — key–value pairs
const visits = new Map();
visits.set('/home', 10);
visits.set('/courses', 4);
visits.get('/home'); // 10
visits.get('/about'); // undefined
visits.has('/about'); // false
visits.size; // 2
visits.delete('/courses');
for (const [page, count] of visits) {
console.log(page, count);
}You can create a Map from an array of pairs — and from an object, via Object.entries:
const prices = new Map([['tea', 20], ['coffee', 35]]);
const fromObject = new Map(Object.entries({ tea: 20, coffee: 35 }));
const backToObject = Object.fromEntries(prices); // { tea: 20, coffee: 35 }keys(), values() and entries() give you iterators, which you can spread into arrays:
[...prices.keys()]; // ['tea', 'coffee']
[...prices.values()]; // [20, 35]Objects as keys
This is something plain objects can’t do — their keys are always turned into strings:
const user1 = { name: 'Asha' };
const user2 = { name: 'Ravi' };
const scores = new Map();
scores.set(user1, 90);
scores.set(user2, 75);
scores.get(user1); // 90
const obj = {};
obj[user1] = 90; // key becomes the string '[object Object]'
obj[user2] = 75; // overwrites it!Keys are matched by identity, like ===. A new object that merely looks the same is a different key: scores.get({ name: 'Asha' }) is undefined.
Map or object?
Use a Map when keys aren’t simple strings (for example, DOM elements or objects), when you add and remove keys often, or when you need the size quickly. Use a plain object for fixed, known fields like a user record.
| Plain object | Map |
|
|---|---|---|
| Key types | strings and symbols | anything |
| Size | Object.keys(obj).length |
map.size |
| Order | mostly insertion (number-like keys first) | always insertion order |
| Looping | Object.entries(obj) |
for…of map directly |
| JSON | works directly | convert with Object.fromEntries first |
| Best for | records with known fields | dynamic lookups and caches |
WeakMap and WeakSet hold objects without stopping them from being garbage-collected — handy for caching data about DOM elements.
const clickCounts = new WeakMap();
button.addEventListener('click', () => {
clickCounts.set(button, (clickCounts.get(button) ?? 0) + 1);
});
// If the button is removed from the page, its entry can be cleaned up automatically.WeakMaps only accept objects as keys and can’t be looped over or sized — the trade-off for not keeping things alive.
Remove duplicates
Write unique(list) that returns a new array without duplicate values, keeping the first occurrence order. Then write countBy(list) that returns a Map of each value to how many times it appears.
function unique(list) {
// your code here
}
function countBy(list) {
// your code here
}
countBy(['a', 'b', 'a']); // Map { 'a' => 2, 'b' => 1 }function unique(list) {
return [...new Set(list)];
}
function countBy(list) {
const counts = new Map();
for (const item of list) {
counts.set(item, (counts.get(item) ?? 0) + 1);
}
return counts;
}Summary
- A
Setstores each value once;haschecks membership quickly. - A
Mapstores key–value pairs and allows any value — even objects — as a key. - Both keep insertion order, have a
size, and work withfor…ofand spread. - Values are compared like
===(withNaNequal to itself), so two look-alike objects are different keys. - Use a plain object for fixed records, a
Mapfor dynamic lookups.