Map & Set — JavaScript

A Map stores key and value pairs. .set() adds or replaces a pair, .get() reads a value, .has() checks for a key, .delete() removes a pair, and .size is the…

Here are today's visitors at the stall: Ana, Sam, Ana, Kim, Sam. You want to know two things: how many different people came, and how many times each person came. An array can hold the list, but an array does not remove the repeated names for you.

For jobs like this, JavaScript has two built-in containers, Map and Set. A Set stores a list of values with no repeats: the same value is kept only once. Put the visitor list in a Set and only Ana, Sam and Kim remain. A Map stores pairs of a key and a value. It is similar to an object, but its keys can be any type. A Map suits a count like "Ana: 2", which means Ana came twice.

Map: key and value pairs

The code below makes a Map, then adds to it, reads from it and replaces a value:

const users = new Map([
  ["ivan", 30],
  ["rio", 25],
]);

users.set("ani", 22);
console.log(users.get("ivan")); // 30
console.log(users.has("rio"));  // true
console.log(users.size);        // 3

users.set("ivan", 31);
console.log(users.get("ivan")); // 31
console.log(users.size);        // 3

Look at the last three lines. Setting a key that is already there does not add a new pair. A Map's keys are unique, so set("ivan", 31) replaces 30, and size stays 3.

The difference from a plain object is in the keys. An object's keys are always turned into text. A Map's keys can be any data type (numbers, text, even objects). The pairs in a Map also keep the order they were added in.

Set: a list with no repeats

The code below makes a Set from an array of five fruit names. Apple and mango are written twice:

const fruits = new Set(["apple", "mango", "apple", "orange", "mango"]);

console.log(fruits.size);           // 3
fruits.add("apple");                // already there, nothing added
console.log(fruits.has("orange"));  // true

So the difference between a Set and an array: an array can hold the same value many times, while a Set keeps it only once.

Drop the repeats from an array

You can use a Set to remove the repeats from an array:

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

console.log(unique); // [1, 2, 3]

The second line works in two steps:

  1. new Set(numbers) makes a Set from that array, so the repeats are removed.
  2. [...] unpacks that Set and puts its values in a new array.

Those three dots are called spread, and the Spread & Rest lesson covers them in full. Array.from(new Set(numbers)) gives the same result. The original array does not change.

Count how often things appear with a Map

The code below counts how many times each colour appears. The key is the colour's name, and the value is that colour's count:

const colors = ["red", "blue", "red"];
const counts = new Map();

for (const c of colors) {
  counts.set(c, (counts.get(c) || 0) + 1);
}

console.log(Object.fromEntries(counts)); // { red: 2, blue: 1 }

⚠️ A Map or a Set is not an array

TL;DR: A Map stores key and value pairs. .set() adds or replaces a pair, .get() reads a value, .has() checks for a key, .delete() removes a pair, and .size is the number of pairs. Its keys are unique and can be any type. A Set stores values without repeats, so [...new Set(array)] is the shortest way to remove the repeats from an array. To count how many times each word appears, use map.set(word, (map.get(word) || 0) + 1) for each word, then Object.fromEntries(map) when you need a plain object.

⚡ Map: key and value pairs

Write:

const users = new Map([
  ["ivan", 30],
  ["rio", 25],
]);

users.set("ani", 22);
users.set("ivan", 31);
console.log(users.size); // ?
Guess first: .set(key, value) puts one pair into the Map, and .size is the number of pairs. What is users.size?

3. The two starting pairs plus ani make three. A Map's keys are unique, so set("ivan", 31) only replaces 30. It does not add a new pair.

Meaning: new Map([...]) makes a Map, which stores key and value pairs. .set() adds a pair or replaces an old value, .get() reads a value, .has() checks whether a key is there, and .size is the number of pairs (not .length). Unlike an object, a Map's keys can be any type, and they keep the order they were added in.

⚡ Set: the same value only once

Write:

const fruits = new Set(["apple", "mango", "apple", "orange", "mango"]);

console.log(fruits.size); // 3

Meaning: A Set stores values without repeats. Apple and mango are written twice, so five items become three. .add() adds one value, but a value that is already there does not change the Set.

⚡ Drop the repeats from an array

Write:

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

Meaning: new Set(...) makes a Set from that array, so the repeats are removed. Then [...] unpacks that Set and puts its values in a new array.

What you will learn