Maps & Sets


In Javascript, there’s two major data types, objects and arrays. An array is a list like structure with numeric indexes to reference the items store there and objects are more of a dictionary, with named references to find what you stored.

const arr: Array<number> = [9, 23, 17, 31];

const obj = {
	name: "Charles",
	status: false,
};

But we can do a little bit better, you also have Map and Set. I like to think of these as super charged versions of objects and arrays respectively but they have their own special use cases.

Maps

Maps are similar to objects except they have some nice built-in helpers to them: .has(), .get(), .set(), .delete() and .clear().

const map = new Map();

map.set("a", 1);
map.set("b", 2);

const b = map.get("b"); // returns 2

map.set("b", 3); // allows us to reset a named key.
map.delete("b");

map.clear(); // removes all entries from the map

Maps are also iterable, so you can loop through them like an array. One of the main differences between objects and maps is that maps respect their insertion order.

const m = new Map<string, number>();

m.set("c", 3);
m.set("a", 1);
m.set("b", 2);

for (const [key, value] of m) {
	console.log(key, value);
}

As we loop through this, the order it would log these elements is “c, 3”, “a, 1”, “b, 2”, where an object might sort the elements alphabetically, we can’t rely on the order of the keys inside an object.

Look up performance in both maps and objects is constant (O(1)) meaning that it’s “instant” look and doesn’t need to traverse the whole input to find an entry. Tests show that map.get("key") can be faster than using object["key"]

Because a map is iterable, if you ever need to transform a map into an object or an array you can use built helpers.

const m = new Map<string, number>();

m.set("c", 3);
m.set("a", 1);
m.set("b", 2);

const arr = Array.from(m);
// [["c", 3], ["a", 1], ["b", 2]]

const obj = Object.fromEntries(m);
// { c: 3, a: 1, b: 2 }

Sets

Sets are similar in that they have a nice API to add and remove and get data out of them.

const s = new Set();

s.add(4);
s.add(5);
s.has(3); // false
s.has(4); // true

The main difference between an array and a set is that sets cannot have two values the same; only one occurance of a value is allowed. Sets de-duplicate their input and like maps respect their insertion order.

const s = new Set();

s.add(4);
s.add(5);
s.add(4);
s.add(3);

s.values();
// SetIterator {4, 5, 3}

Even though we added 4 twice, we only have one occurence of this value. Sets are iterable too, so again, you can loop their values:

const s = new Set();

s.add(4);
s.add(5);
s.add(4);
s.add(3);

for (let item of s) {
	console.log(item);
}

// 4
// 5
// 3