JavaScript Tutorial · Objects and Arrays · Lesson 26 of 44
JavaScript Map and Set
Key-value maps with any key type, and sets of unique values.
Set — unique values
A Set stores each value once. It's the quickest way to remove duplicates or check membership:
const tags = new Set(["js", "css", "js", "html", "css"]);
console.log(tags.size);
console.log(tags.has("js"), tags.has("go"));
tags.add("go");
tags.delete("css");
console.log([...tags]);
console.log([...new Set([3, 1, 3, 2, 1])]);
Output
3 true false [ 'js', 'html', 'go' ] [ 3, 1, 2 ]
Map — key-value pairs
A Map is like an object but keys can be any type (objects, numbers…), it remembers insertion order, and it has a size. Prefer Map for dictionaries that change at runtime:
const visits = new Map();
visits.set("/home", 10);
visits.set("/about", 3);
visits.set("/home", visits.get("/home") + 1);
console.log(visits.get("/home"), visits.size);
for (const [path, count] of visits) {
console.log(path, count);
}
const objKey = { id: 1 };
const meta = new Map([[objKey, "an object as a key"]]);
console.log(meta.get(objKey));
Output
11 2 /home 11 /about 3 an object as a key
Counting with a Map
const words = "the cat and the hat and the bat".split(" ");
const counts = new Map();
for (const w of words) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(counts);
Output
Map(5) { 'the' => 3, 'cat' => 1, 'and' => 2, 'hat' => 1, 'bat' => 1 }Hash maps and sets are the most common tools in coding interviews — practise with Two Sum and Contains Duplicate.
Test yourself
What is the quickest way to remove duplicates from an array arr?
arr.unique()[...new Set(arr)]new Map(arr)arr.distinct()
Show answer
Answer: [...new Set(arr)]
Practice next
- Two Sum · coding problem
- Contains Duplicate · coding problem
- Top K Frequent Elements · coding problem