JavaScript Map and Set
Map and Set are two built-in collections. A Map stores key-value pairs, and a Set stores a list of values with no duplicates.
Set: Unique Values
A Set keeps each value only once. If you add the same value again, nothing happens.
Example
const visitors = new Set();
visitors.add("Ali");
visitors.add("Sana");
visitors.add("Ali"); // already there, ignored
console.log(visitors.size); // 2
console.log(visitors.has("Sana")); // true
visitors.delete("Sana");
console.log([...visitors]); // [ 'Ali' ]Set Methods
| Method | What it does |
|---|---|
new Set(array) | Creates a set, optionally from an array |
add(value) | Adds a value |
has(value) | true if the value is in the set |
delete(value) | Removes a value |
clear() | Removes everything |
size | How many values (a property, not a method) |
Removing Duplicates From an Array
The most common use of a Set is cleaning an array in one line:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const orders = ["Chai", "Samosa", "Chai", "Paratha", "Samosa", "Chai"];
const menuItems = [...new Set(orders)];
document.getElementById("demo").innerHTML =
"All orders: " + orders.join(", ") + "<br>" +
"Different items: " + menuItems.join(", ");
</script>
</body>
</html>Try it Yourself »All orders: Chai, Samosa, Chai, Paratha, Samosa, Chai Different items: Chai, Samosa, Paratha
Set Operations
Modern browsers give sets methods to compare two sets. Each returns a new Set:
Example
const pythonClass = new Set(["Ali", "Sana", "Hamza"]);
const webClass = new Set(["Sana", "Zara", "Hamza"]);
console.log([...pythonClass.union(webClass)]); // everyone
console.log([...pythonClass.intersection(webClass)]); // in both
console.log([...pythonClass.difference(webClass)]); // only Python[ 'Ali', 'Sana', 'Hamza', 'Zara' ] [ 'Sana', 'Hamza' ] [ 'Ali' ]
Map: Key-Value Pairs
A Map is like an object, but with some important differences:
- Keys can be any type: numbers, objects, even functions, not only strings
- It remembers the order in which you added items
- It has a
sizeproperty and easy methods
Example
const stock = new Map();
stock.set("rice", 40);
stock.set("sugar", 15);
stock.set("oil", 0);
console.log(stock.get("rice")); // 40
console.log(stock.has("flour")); // false
console.log(stock.size); // 3
stock.set("sugar", stock.get("sugar") - 5); // update
stock.delete("oil");| Method | What it does |
|---|---|
set(key, value) | Adds or updates a pair |
get(key) | Reads the value (or undefined) |
has(key) | true if the key exists |
delete(key) | Removes a pair |
size | Number of pairs |
Looping Through a Map
for...of gives each pair as [key, value], which you can destructure:
Example
<!DOCTYPE html>
<html>
<body>
<h3>Exam Results</h3>
<ul id="list"></ul>
<script>
const results = new Map([
["Ayesha", 91],
["Bilal", 67],
["Zainab", 84]
]);
for (const [name, marks] of results) {
const li = document.createElement("li");
li.textContent = name + ": " + marks;
document.getElementById("list").append(li);
}
</script>
</body>
</html>Try it Yourself »You can also use results.keys(), results.values(), results.entries() and results.forEach((value, key) => ...).
Counting With a Map
Maps are perfect for counting how often something appears:
Example
const words = "chai chai coffee chai lassi coffee".split(" ");
const count = new Map();
for (const w of words) {
count.set(w, (count.get(w) ?? 0) + 1);
}
console.log(Object.fromEntries(count));{ chai: 3, coffee: 2, lassi: 1 }Object.fromEntries() turns a Map into a normal object, and new Map(Object.entries(obj)) does the opposite.
Which One Should I Use?
| Use | When |
|---|---|
| Array | An ordered list, duplicates allowed |
| Set | A list where every value must be unique |
| Object | A fixed record with known string keys, like a student's details |
| Map | Keys added and removed often, or keys that are not strings |
JSON.stringify does not understand Maps and Sets. Convert them first with [...set] or Object.fromEntries(map).
Exercise
Exercise
What is the value of new Set([1, 2, 2, 3, 3, 3]).size?
