JavaScript Map and Set: Store Keys and Unique Values
Use a Set when a collection should contain unique values. Use a Map when each key needs a value and the keys may be more varied than an object’s property names.
Keep unique values in a Set
Adding the same value more than once does not create a duplicate. Use add() to insert a value, has() to check for it, and size to read the number of unique entries:
const tags = new Set();
tags.add("html");
tags.add("css");
tags.add("html");
console.log(tags.size); // 2
console.log(tags.has("css")); // true
You can create a Set from an array to remove repeated values. Spread it into a new array when you need an array result:
const names = ["Asha", "Ravi", "Asha"];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames); // ["Asha", "Ravi"]
Store key-value pairs in a Map
A Map keeps keys and values together. Its keys can be strings, numbers, objects or other values. Use set(), get() and has() to work with entries:
const stock = new Map();
stock.set("Notebook", 12);
stock.set("Pen", 30);
console.log(stock.get("Notebook")); // 12
console.log(stock.has("Pen")); // true
Maps are iterable, so a for...of loop can read each key and value:
for (const [item, quantity] of stock) {
console.log(`${item}: ${quantity}`);
}
Choose Map, Set, object or array
- Use a
Setwhen you need unique values and quick membership checks. - Use a
Mapfor a collection of entries whose keys may be any value or change over time. - Use an object for a record with a known set of named properties.
- Use an array for an ordered list, including a list that may contain repeated values.
A Map is different from the array map() method. Map is a collection type; map() transforms each item in an array and returns a new array.
Common questions about Map and Set
How do I remove a value from a Set or Map?
Call delete(value) on a Set or delete(key) on a Map. Call clear() to remove every entry.
Do Map and Set keep insertion order?
Yes. Iteration follows the order in which entries were first added. Adding an existing Set value does not create a second entry.