Map and Set

Map, a dictionary with keys of any type, and Set, a collection of unique values: iteration, conversions, set operations, WeakMap and WeakSet, and the counting, deduplication and grouping patterns.

  • Intermediate
  • 22 min
  • 12 questions
  • Lesson 11 of 39

In this lesson you will learn

  • Choose between a Map and an object, a Set and an array, and explain why
  • Iterate over Maps and Sets and convert them to arrays, objects and JSON
  • Apply set operations and the counting, deduplication and grouping patterns
  • Explain what WeakMap and WeakSet are for and why they have no size

The school olympiad has received 500 registrations. Some students pressed «Send» twice, and you need to know how many came from each city and who signed up for both maths and informatics. Plain objects and arrays can do this, but clumsily: searching an array is slow, and an object turns every key into a string. JavaScript has two collections built for exactly these jobs: Map (key → value) and Set (unique values). In this lesson you will learn when to use them instead of objects and arrays, how to iterate over them and convert them, and what WeakMap and WeakSet are for.

Map: a dictionary with keys of any type

MapDefinition

A collection of key–value pairs in which a key can be any value: a string, a number, an object, even a function. Entries are kept in the order they were added.

You create an empty map with new Map(), or pass the constructor an array of [key, value] pairs. Five methods cover almost everything: set(key, value) adds or replaces, get(key) reads (it returns undefined when the key is missing), has(key) checks, delete(key) removes and clear() empties the map. The size property is the number of entries. Because set returns the map itself, calls can be chained.

JavaScript
const capitals = new Map();
capitals.set('Azerbaijan', 'Baku');
capitals.set('Georgia', 'Tbilisi').set('Türkiye', 'Ankara');

console.log(capitals.get('Georgia'));
console.log(capitals.get('France'));
console.log(capitals.has('Azerbaijan'));
console.log(capitals.size);

capitals.delete('Türkiye');
console.log(capitals);
Expected output
Tbilisi
undefined
true
3
Map(2) { 'Azerbaijan' => 'Baku', 'Georgia' => 'Tbilisi' }

So why is a plain object not enough? An object’s keys are always strings (or symbols): the number 1 silently becomes the string '1', and an object used as a key becomes the string '[object Object]' — so all objects collide in a single key. A Map compares keys without any conversion.

JavaScript
const obj = {};
obj[1] = 'number one';
obj['1'] = 'string one';
console.log(Object.keys(obj));

const map = new Map();
map.set(1, 'number one');
map.set('1', 'string one');
console.log(map.size, map.get(1), map.get('1'));

const leyla = { name: 'Leyla' };
const elvin = { name: 'Elvin' };
const scores = {};
scores[leyla] = 95;
scores[elvin] = 80;
console.log(scores);

const scoreMap = new Map([[leyla, 95], [elvin, 80]]);
console.log(scoreMap.get(leyla), scoreMap.get(elvin));
Expected output
[ '1' ]
2 number one string one
{ '[object Object]': 80 }
95 80

In the object, the second assignment overwrote the first, and Elvin’s score replaced Leyla’s, because both objects turned into the same string. The Map kept all four entries apart. There is one more trap: a plain object inherits properties from Object.prototype. When the keys come from users (words in a text, user names), a word such as toString or constructor is already «there» before you add it:

JavaScript
const words = ['map', 'toString', 'map'];

const counts = {};
for (const w of words) counts[w] = (counts[w] || 0) + 1;
console.log(counts.map, typeof counts.toString);

const safe = new Map();
for (const w of words) safe.set(w, (safe.get(w) ?? 0) + 1);
console.log(safe.get('map'), safe.get('toString'));
Expected output
2 string
2 1

counts.toString was already a function, and «function + 1» produced a string, so the count was corrupted. A Map has no inherited keys, so its result is correct. The table below compares the two tools.

FeatureObject {}Map
Key typesstrings and symbolsany value
Order of keysinteger-like keys first, ascending, then the rest in insertion orderalways insertion order
Number of entriesObject.keys(obj).lengthmap.size
Iterationthrough Object.keys/values/entriesdirectly with for...of
Inherited keysyes (toString, constructor)none
JSONJSON.stringify worksgives {} — convert it first
Best forone record with known fields (a user, settings)a dictionary that grows and shrinks, with keys taken from data

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

Set: unique values only

SetDefinition

A collection in which every value occurs at most once (like a set in mathematics). Adding a value that is already there changes nothing.

Its methods are add(value), has(value), delete(value), clear() and the size property. new Set(iterable) fills the set from an array, a string or another set. That gives the shortest way to remove duplicates in JavaScript: [...new Set(array)].

JavaScript
const visited = new Set();
visited.add('Baku');
visited.add('Ganja');
visited.add('Baku');
console.log(visited.size);
console.log(visited.has('Ganja'), visited.has('Shaki'));
visited.delete('Ganja');
console.log(visited);

const marks = [5, 4, 5, 3, 4, 5];
const unique = [...new Set(marks)];
console.log(unique);
console.log(new Set([1, '1', NaN, NaN, 0, -0]));
Expected output
2
true false
Set(1) { 'Baku' }
[ 5, 4, 3 ]
Set(4) { 1, '1', NaN, 0 }

How does a Set decide that two values are «the same»? It uses the SameValueZero rule: it works like ===, except that NaN counts as equal to NaN (and 0 equals -0). That is why 1 and '1' both stay, while two NaNs become one. Maps compare keys by the same rule. Objects and arrays, however, are compared by reference, not by contents: two objects that look alike are two different values, and a newly written [1, 2] array is never equal to an earlier one.

JavaScript
const a = { id: 1 };
const b = { id: 1 };
const people = new Set([a, b, a]);
console.log(people.size);

const ids = new Set([a.id, b.id]);
console.log(ids.size);

const m = new Map();
m.set([1, 2], 'pair');
console.log(m.get([1, 2]));
Expected output
2
1
undefined

To remove duplicate objects, put a primitive key in the Set — an id, an email — not the object itself: ids.size is 1 because the number 1 is the same value both times. m.get([1, 2]) returned undefined because it is a new array, not the array stored as the key.

Order, iteration and conversions

Maps and sets remember the insertion order, and every way of walking through them follows it. for...of over a Map gives [key, value] pairs, which are easy to destructure. keys(), values() and entries() return iterators; spread them into an array with [...] when you need array methods. Watch the order of the forEach parameters: as with arrays, the value comes first, then the key.

JavaScript
const prices = new Map([
  ['bread', 0.7],
  ['milk', 1.6],
  ['tea', 4.5],
]);

for (const [item, price] of prices) {
  console.log(`${item}: ${price} AZN`);
}
console.log([...prices.keys()]);
console.log([...prices.values()]);
prices.forEach((value, key) => console.log(key, '->', value));

const tags = new Set(['js', 'css']);
tags.add('html');
for (const tag of tags) console.log(tag);
Expected output
bread: 0.7 AZN
milk: 1.6 AZN
tea: 4.5 AZN
[ 'bread', 'milk', 'tea' ]
[ 0.7, 1.6, 4.5 ]
bread -> 0.7
milk -> 1.6
tea -> 4.5
js
css
html

Objects have a surprise here: integer-like keys always come first, in ascending order, and only then the other keys in insertion order. A Map keeps exactly the order you used:

JavaScript
const obj = { b: 'first', 2: 'second', 1: 'third' };
console.log(Object.keys(obj));

const map = new Map([['b', 'first'], [2, 'second'], [1, 'third']]);
console.log([...map.keys()]);
Expected output
[ '1', '2', 'b' ]
[ 'b', 2, 1 ]

A Map and Object.entries speak the same «language» — an array of [key, value] pairs. That is why every conversion is a one-liner: array → Set new Set(array), Set → array [...set] or Array.from(set); object → Map new Map(Object.entries(obj)), Map → object Object.fromEntries(map); Map → array of pairs [...map].

JavaScript
const stock = { pen: 12, notebook: 5 };
const stockMap = new Map(Object.entries(stock));
stockMap.set('eraser', 0);
console.log(stockMap);

const back = Object.fromEntries(stockMap);
console.log(back);

console.log(JSON.stringify(stockMap));
console.log(JSON.stringify(Object.fromEntries(stockMap)));
console.log(JSON.stringify([...stockMap]));

const restored = new Map(JSON.parse('[["pen",12],["eraser",0]]'));
console.log(restored.get('pen'));
Expected output
Map(3) { 'pen' => 12, 'notebook' => 5, 'eraser' => 0 }
{ pen: 12, notebook: 5, eraser: 0 }
{}
{"pen":12,"notebook":5,"eraser":0}
[["pen",12],["notebook",5],["eraser",0]]
12

Set operations: union, intersection, difference

Sets come from mathematics, and so do their operations. Since mid-2024 all major browsers and Node.js 22+ have built-in methods for them (they became part of the ES2025 standard): union (A ∪ B), intersection (A ∩ B), difference (A \ B), symmetricDifference (in exactly one of the two), plus the checks isSubsetOf, isSupersetOf and isDisjointFrom. Each method returns a new Set and leaves the originals unchanged.

JavaScript
const math = new Set(['Aysel', 'Murad', 'Leyla', 'Elvin']);
const informatics = new Set(['Leyla', 'Nigar', 'Murad']);

console.log(math.union(informatics));
console.log(math.intersection(informatics));
console.log(math.difference(informatics));
console.log(math.symmetricDifference(informatics));
console.log(new Set(['Leyla']).isSubsetOf(math));
console.log(math.isDisjointFrom(new Set(['Kamal'])));
Expected output
Set(5) { 'Aysel', 'Murad', 'Leyla', 'Elvin', 'Nigar' }
Set(2) { 'Leyla', 'Murad' }
Set(2) { 'Aysel', 'Elvin' }
Set(3) { 'Aysel', 'Elvin', 'Nigar' }
true
true

Browsers older than 2024 lack these methods. The same results come from the filter + has pair, which works everywhere, and checking typeof Set.prototype.union tells you which way to go. This version is fast too: informatics.has(name) is quick, so the intersection takes a single pass over the first set.

JavaScript
const math = new Set(['Aysel', 'Murad', 'Leyla', 'Elvin']);
const informatics = new Set(['Leyla', 'Nigar', 'Murad']);

const both = [...math].filter((name) => informatics.has(name));
const onlyMath = [...math].filter((name) => !informatics.has(name));
const all = new Set([...math, ...informatics]);

console.log(both);
console.log(onlyMath);
console.log(all.size);
console.log(typeof Set.prototype.union === 'function' ? 'native union available' : 'use the fallback');
Expected output
[ 'Murad', 'Leyla' ]
[ 'Aysel', 'Elvin' ]
5
native union available

WeakMap and WeakSet

Weak referenceDefinition

A WeakMap or WeakSet holds its keys weakly: if no other part of the program refers to a key object any more, the garbage collector may delete it, and its entry disappears from the collection too.

That is why the rules differ from Map and Set: keys can only be objects (and non-registered symbols); there is no size, no clear() and no iteration — the contents can vanish at any moment, so the language does not let you list them. Only set/get/has/delete remain (add/has/delete in a WeakSet). Typical uses: attaching extra data or a cache to objects you do not own (DOM elements, objects from a library) and marking objects as «already processed». When the object goes away, its data goes with it, and no memory leaks.

JavaScript
const processed = new WeakSet();
const cache = new WeakMap();

function total(cart) {
  if (cache.has(cart)) return cache.get(cart) + ' (from cache)';
  const sum = cart.items.reduce((s, item) => s + item.price, 0);
  cache.set(cart, sum);
  return sum;
}

let cart = { items: [{ price: 4.5 }, { price: 1.6 }] };
console.log(total(cart));
console.log(total(cart));

processed.add(cart);
console.log(processed.has(cart), processed.has({ ...cart }));

try {
  cache.set('cart-1', 10);
} catch (error) {
  console.log(error.name);
}
console.log(cache.size, typeof cache.keys);
cart = null;
Expected output
6.1
6.1 (from cache)
true false
TypeError
undefined undefined

Typical tasks and a mini project

Programmers use Map and Set most often for three jobs: counting, removing duplicates and grouping. The counting algorithm is always the same:

  1. Create an empty Map

    const counts = new Map(); — the key is the thing being counted, the value is its count.

  2. Find the key of each item

    A word, a city, a mark — whatever you are counting.

  3. Increase the counter

    counts.set(key, (counts.get(key) ?? 0) + 1) — if the key is missing, ?? 0 starts from zero.

  4. Read or sort the result

    [...counts].sort((a, b) => b[1] - a[1]) puts the most frequent first.

JavaScript
const text = 'the cat and the dog and the bird';
const freq = new Map();
for (const word of text.split(' ')) {
  freq.set(word, (freq.get(word) ?? 0) + 1);
}
console.log(freq);

const top = [...freq].sort((x, y) => y[1] - x[1]).slice(0, 2);
console.log(top);
Expected output
Map(5) { 'the' => 3, 'cat' => 1, 'and' => 2, 'dog' => 1, 'bird' => 1 }
[ [ 'the', 3 ], [ 'and', 2 ] ]

Grouping is the same idea, but the value is an array: if the key is missing, create an empty array, then push the item into it. Since ES2024 there is also a built-in version: Map.groupBy(items, fn) (and Object.groupBy, which returns an object).

JavaScript
const students = [
  { name: 'Aysel', city: 'Baku' },
  { name: 'Murad', city: 'Ganja' },
  { name: 'Leyla', city: 'Baku' },
  { name: 'Elvin', city: 'Shaki' },
];

const byCity = new Map();
for (const s of students) {
  if (!byCity.has(s.city)) byCity.set(s.city, []);
  byCity.get(s.city).push(s.name);
}
for (const [city, names] of byCity) console.log(city, names);

const grouped = Map.groupBy(students, (s) => s.city);
console.log(grouped.get('Baku').length, [...grouped.keys()]);
Expected output
Baku [ 'Aysel', 'Leyla' ]
Ganja [ 'Murad' ]
Shaki [ 'Elvin' ]
2 [ 'Baku', 'Ganja', 'Shaki' ]

Now let’s solve the olympiad task from the beginning of the lesson. A Set of email|subject keys drops repeated registrations, a Map counts registrations per city, and a Map of «subject → Set of names» collects the participants of each subject; the intersection of the two sets gives the students entered in both subjects.

JavaScript
const registrations = [
  { email: 'aysel@mail.az', name: 'Aysel', city: 'Baku', subject: 'math' },
  { email: 'murad@mail.az', name: 'Murad', city: 'Ganja', subject: 'math' },
  { email: 'aysel@mail.az', name: 'Aysel', city: 'Baku', subject: 'math' },
  { email: 'leyla@mail.az', name: 'Leyla', city: 'Baku', subject: 'it' },
  { email: 'murad@mail.az', name: 'Murad', city: 'Ganja', subject: 'it' },
  { email: 'nigar@mail.az', name: 'Nigar', city: 'Shaki', subject: 'it' },
];

const seen = new Set();
const bySubject = new Map();
const perCity = new Map();
for (const r of registrations) {
  const key = `${r.email}|${r.subject}`;
  if (seen.has(key)) continue;
  seen.add(key);
  if (!bySubject.has(r.subject)) bySubject.set(r.subject, new Set());
  bySubject.get(r.subject).add(r.name);
  perCity.set(r.city, (perCity.get(r.city) ?? 0) + 1);
}

console.log('unique registrations:', seen.size);
console.log(perCity);
console.log('both subjects:', [...bySubject.get('math').intersection(bySubject.get('it'))]);
Expected output
unique registrations: 5
Map(3) { 'Baku' => 2, 'Ganja' => 2, 'Shaki' => 1 }
both subjects: [ 'Murad' ]

Aysel signed up for the same subject twice, so five of the six registrations remain. Murad entered two different subjects — that is not a duplicate, which is why the key includes the subject. The code below shows two frequent mistakes.

JavaScript
console.log(new Set('hello'));
console.log(new Set(['hello']));

const map = new Map();
map['Baku'] = 2300000;
console.log(map.size, map.get('Baku'));
Expected output
Set(4) { 'h', 'e', 'l', 'o' }
Set(1) { 'hello' }
0 undefined

Exercise

Count how many times each mark appears in the grades array using a Map, and print every entry as mark: count in order of first appearance.

Exercise · JavaScript
const grades = [5, 4, 5, 3, 5, 4];
const counts = new Map();
// count each mark, then print "mark: count" lines
Expected output
5: 3
4: 2
3: 1

Exercise

Aysel’s and Murad’s friend lists contain repeats. Print three lines: 1) the number of Aysel’s unique friends; 2) the common friends as an alphabetically sorted array; 3) the friends only Aysel has, sorted alphabetically. Use filter and has so it works in older browsers too.

Exercise · JavaScript
const aysel = ['Leyla', 'Elvin', 'Nigar', 'Leyla', 'Kamal'];
const murad = ['Elvin', 'Orxan', 'Kamal', 'Elvin'];
// 1) unique count  2) common, sorted  3) only Aysel, sorted
Expected output
4
[ 'Elvin', 'Kamal' ]
[ 'Leyla', 'Nigar' ]

Remember

  • Map is a key → value collection with keys of any type: set/get/has/delete, size, insertion order and no inherited keys.
  • Set keeps unique values by the SameValueZero rule; [...new Set(arr)] removes duplicates, while objects are compared by reference.
  • Conversions go through an array of pairs: new Map(Object.entries(obj)), Object.fromEntries(map), [...map]; JSON.stringify(map) gives {}.
  • union, intersection, difference and symmetricDifference (ES2025) return new sets; for older browsers use filter + has.
  • WeakMap/WeakSet hold object keys weakly, with no size and no iteration — for caches and marks tied to objects.
Spotted a mistake or something inaccurate in this lesson?

Check yourself

12 questions. Every correct answer earns XP.

Question 1 / 12

Question 1 / 12. What is printed?
const m = new Map(); m.set('a', 1).set('a', 2); console.log(m.size, m.get('a'));