DevPath · Learn to code ESPTEN

Data structures

Map and Set

Map and Set

Beyond objects and arrays, JavaScript offers two specialized structures.

Map: key-value pairs

A Map associates keys with values. Unlike a normal object, its keys can be of any type (even objects or functions) and it remembers the insertion order.

const stock = new Map();
stock.set("apples", 50);
stock.set("pears", 30);

console.log(stock.get("apples")); // 50
console.log(stock.has("pears"));  // true
console.log(stock.size);          // 2
stock.delete("pears");

You can iterate over it easily:

for (const [fruit, amount] of stock) {
  console.log(fruit, amount);
}

Set: unique values

A Set is a collection of values without duplicates.

const tags = new Set(["js", "web", "js"]);
console.log(tags.size); // 2 (the duplicate is ignored)
tags.add("css");
console.log(tags.has("web")); // true

A common trick: remove duplicates from an array.

const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]

When to use each one?

Examples

Counting frequencies with Map

const words = ["sun", "sea", "sun", "light", "sea", "sun"];
const count = new Map();
for (const w of words) {
  count.set(w, (count.get(w) || 0) + 1);
}
console.log([...count.entries()]);

Union of two sets with Set

const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
const union = new Set([...a, ...b]);
console.log([...union]);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Stacks and queues →