Skip to content

Maps & Sets

A Map holds key-value pairs, like an object, and a Set holds a list of values, like an array, in which each value can appear only once. Both remember the order in which entries were added, both report their length through a size property, and both are iterable, so they work with for...of and the spread syntax.

set adds or replaces an entry and returns the map, so calls can be chained. get reads a value, has tests for a key, delete removes one entry and clear removes them all.

const stock = new Map();
stock.set('apples', 12);
stock.set('pears', 4).set('plums', 0);
console.log(stock.get('pears'));
console.log(stock.has('plums'), stock.has('figs'));
console.log(stock.size);
stock.delete('plums');
console.log(stock);

This prints:

4
true false
3
Map(2) { 'apples' => 12, 'pears' => 4 }

An object’s keys are always strings or symbols, but a map’s keys can be any value, including objects and numbers. Keys are compared much like ===, so the number 1 and the string '1' are separate keys, and an object key matches only that same object.

const visits = new Map();
const home = { path: '/' };
const about = { path: '/about' };
visits.set(home, 10);
visits.set(about, 3);
visits.set(1, 'number key');
visits.set('1', 'string key');
console.log(visits.get(home));
console.log(visits.get(1), visits.get('1'));

This prints:

10
number key string key

The one difference from === is that NaN matches itself as a key.

new Map() accepts any iterable of [key, value] pairs. A plain object is not iterable, so pass it through Object.entries first, and use Object.fromEntries to turn a map back into an object. Looping over a map gives [key, value] pairs, and the keys, values and entries methods return iterators that the spread syntax turns into arrays.

const prices = { tea: 2.5, coffee: 3.1 };
const priceMap = new Map(Object.entries(prices));
for (const [drink, price] of priceMap) {
console.log(`${drink}: £${price.toFixed(2)}`);
}
console.log([...priceMap.keys()]);
console.log(Object.fromEntries(priceMap));

This prints:

tea: £2.50
coffee: £3.10
[ 'tea', 'coffee' ]
{ tea: 2.5, coffee: 3.1 }

Map.groupBy (ES2024) builds a map by grouping the items of an array with a callback, where the callback’s return value becomes the key.

const orders = [
{ id: 1, status: 'shipped' },
{ id: 2, status: 'pending' },
{ id: 3, status: 'shipped' },
];
const byStatus = Map.groupBy(orders, (order) => order.status);
console.log(byStatus.get('shipped'));

This prints:

[ { id: 1, status: 'shipped' }, { id: 3, status: 'shipped' } ]

Choose a map over an object when the keys are not known in advance, are not strings, or are added and removed often. An object remains the better fit for a record with fixed, named fields, and it is what JSON.stringify understands.

A set drops any value it already holds, so building one from an array is the shortest way to remove duplicates. add, has, delete and clear work as their map counterparts do.

const tags = new Set(['news', 'sport', 'news', 'weather', 'sport']);
console.log(tags);
console.log(tags.size);
console.log(tags.has('sport'));
tags.add('travel');
tags.add('news');
tags.delete('weather');
console.log([...tags]);

This prints:

Set(3) { 'news', 'sport', 'weather' }
3
true
[ 'news', 'sport', 'travel' ]

has on a set is much faster than includes on a long array, because a set does not have to scan its values. Uniqueness uses the same comparison as map keys, so two objects with identical contents are still two different values. Avoiding Duplicate Array Values shows more ways to remove duplicates.

Since ES2025, sets have methods that combine two sets into a new one, which current browsers and Node 22 or later support. union, intersection, difference and symmetricDifference return a new set, while isSubsetOf, isSupersetOf and isDisjointFrom return a boolean.

const morning = new Set(['Ana', 'Ben', 'Chloe']);
const evening = new Set(['Ben', 'Dev', 'Chloe']);
console.log(morning.union(evening));
console.log(morning.intersection(evening));
console.log(morning.difference(evening));
console.log(morning.isSubsetOf(new Set(['Ana', 'Ben', 'Chloe', 'Dev'])));

This prints:

Set(4) { 'Ana', 'Ben', 'Chloe', 'Dev' }
Set(2) { 'Ben', 'Chloe' }
Set(1) { 'Ana' }
true

WeakMap and WeakSet are related types whose keys or values must be objects, or symbols that are not in the global registry, and which do not stop those keys or values being garbage-collected. They cannot be looped over, and suit attaching extra data to objects that your code does not own.

Steve Griffith covers this topic in his video The Differences between ES6 Maps and Sets.