Plain objects and arrays can do a lot, but two built-in collections often fit a job better. A Map stores key-value pairs where the key can be anything, even an object, and it remembers the order you added them. A Set keeps a list in which every value appears only once. This lesson shows when to reach for each one, with examples such as removing duplicates and counting words.
In this lesson you will learn
- Creating a
Mapand usingset,get,has,deleteandsize - Looping over a Map and converting it to and from an object
- Creating a
Setand removing duplicates from an array - Union, intersection and difference of sets
- When to choose Map or Set over objects and arrays
You should already know objects and arrays.
Map
// Map: key-value pairs where keys can be any type
const stock = new Map();
stock.set("pen", 40);
stock.set("notebook", 25);
stock.set("eraser", 0);
console.log(stock.get("pen")); // read a value
console.log(stock.has("ruler")); // check a key
console.log(stock.size); // number of entries
stock.set("pen", 35); // update
stock.delete("eraser"); // remove
for (const [item, qty] of stock) {
console.log(`${item}: ${qty}`);
}
// Object keys are allowed too
const visits = new Map();
const user = { name: "Rafi" };
visits.set(user, 3);
console.log(visits.get(user));
// Convert between objects and maps
const prices = new Map(Object.entries({ tea: 20, coffee: 60 }));
console.log(prices);
console.log(Object.fromEntries(prices));
Output
40
false
3
pen: 35
notebook: 25
3
Map(2) { 'tea' => 20, 'coffee' => 60 }
{ tea: 20, coffee: 60 }
new Map()creates an empty map.set(key, value)adds or replaces an entry, andget(key)reads it back (or returnsundefined).haschecks for a key,deleteremoves one, andsizeis a property, not a method.for (const [key, value] of map)visits entries in the order they were inserted.- Any value can be a key. Here the
userobject itself is the key, something a plain object cannot do because its keys are always turned into strings. new Map(Object.entries(obj))andObject.fromEntries(map)convert between the two forms, which is handy before sending data as JSON.
Set
// Set: a collection of unique values
const tags = new Set(["html", "css", "js"]);
tags.add("css"); // already there, ignored
tags.add("python");
console.log(tags.size);
console.log(tags.has("js"));
// Remove duplicates from an array
const marks = [70, 85, 70, 92, 85, 60];
const unique = [...new Set(marks)];
console.log(unique);
// Union, intersection and difference
const a = new Set(["Ana", "Bilal", "Chen"]);
const b = new Set(["Bilal", "Dina"]);
console.log([...new Set([...a, ...b])]);
console.log([...a].filter(x => b.has(x)));
console.log([...a].filter(x => !b.has(x)));
// Counting words with a Map
const text = "to be or not to be";
const count = new Map();
for (const w of text.split(" ")) {
count.set(w, (count.get(w) ?? 0) + 1);
}
console.log(count);
Output
4
true
[ 70, 85, 92, 60 ]
[ 'Ana', 'Bilal', 'Chen', 'Dina' ]
[ 'Bilal' ]
[ 'Ana', 'Chen' ]
Map(4) { 'to' => 2, 'be' => 2, 'or' => 1, 'not' => 1 }
- Adding a value that is already in a Set does nothing, so
sizestays at 4. [...new Set(array)]is the shortest way to remove duplicates while keeping the first-seen order.hason a Set is very fast even for thousands of items, much faster thanarray.includeson a long array.- Union combines both sets; intersection keeps values in both (
filterwithb.has); difference keeps values only in the first. Recent browsers also offer built-in methods such asa.union(b)anda.intersection(b). - The word counter uses
count.get(w) ?? 0to start each new word at zero.
Map vs Object, Set vs Array
| Need | Best choice | Why |
|---|---|---|
| Fixed record such as a user profile | Object | Simple syntax, works with JSON |
| Lookup table that grows and shrinks | Map | Fast add/delete, has size, any key type |
| Keys that are objects or DOM elements | Map (or WeakMap) | Object keys would become strings |
| Ordered list, duplicates allowed | Array | Indexes, sorting, map/filter |
| Unique values, fast “is it there?” | Set | No duplicates, fast has |
WeakMap and WeakSet are versions whose keys must be objects and are not kept alive by the collection, so data attached to a removed DOM element can be cleaned up automatically. They cannot be looped over.
Common Mistakes
- Using square brackets on a Map:
map["pen"] = 5sets an ordinary property, not a Map entry. Usemap.set. - Calling
size()as a function; it is a property. - Expecting
JSON.stringify(map)to work; it gives{}. Convert withObject.fromEntriesfirst. - Expecting a Set to remove duplicate objects with the same contents; two separate objects are always different values.
Practice Exercises
Exercise 1. Given ["dhaka", "sylhet", "dhaka", "khulna", "sylhet"], print how many unique cities there are.
Show answer
const cities = ["dhaka", "sylhet", "dhaka", "khulna", "sylhet"];
console.log(new Set(cities).size); // 3
Exercise 2. Group students by department using a Map whose values are arrays of names.
Show answer
const students = [["Ana", "CSE"], ["Rafi", "EEE"], ["Mitu", "CSE"]];
const byDept = new Map();
for (const [name, dept] of students) {
if (!byDept.has(dept)) byDept.set(dept, []);
byDept.get(dept).push(name);
}
console.log(byDept); // Map(2) { 'CSE' => ['Ana', 'Mitu'], 'EEE' => ['Rafi'] }
Modern JavaScript also has Map.groupBy(students, s => s[1]) for this.
Frequently Asked Questions
Is a Map faster than an object?
For collections where keys are added and removed often, Map is usually faster and is designed for that use. For small fixed records the difference does not matter, and objects are simpler.
Does a Set keep insertion order?
Yes. Both Map and Set iterate in the order items were first added.
Summary
- Map: key-value pairs with any key type, insertion order and a
size. - Set: unique values with fast
has. [...new Set(arr)]removes duplicates.- Use objects for fixed records and Maps for changing lookup tables.
