Reading history

JavaScript Map and Set (with Examples)

5 min read 0 views

Learn JavaScript Map and Set: storing key-value pairs with any key type, removing duplicates, set union and intersection, word counting and WeakMap.

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 Map and using set, get, has, delete and size
  • Looping over a Map and converting it to and from an object
  • Creating a Set and 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, and get(key) reads it back (or returns undefined).
  • has checks for a key, delete removes one, and size is 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 user object itself is the key, something a plain object cannot do because its keys are always turned into strings.
  • new Map(Object.entries(obj)) and Object.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 size stays at 4.
  • [...new Set(array)] is the shortest way to remove duplicates while keeping the first-seen order.
  • has on a Set is very fast even for thousands of items, much faster than array.includes on a long array.
  • Union combines both sets; intersection keeps values in both (filter with b.has); difference keeps values only in the first. Recent browsers also offer built-in methods such as a.union(b) and a.intersection(b).
  • The word counter uses count.get(w) ?? 0 to start each new word at zero.

Map vs Object, Set vs Array

NeedBest choiceWhy
Fixed record such as a user profileObjectSimple syntax, works with JSON
Lookup table that grows and shrinksMapFast add/delete, has size, any key type
Keys that are objects or DOM elementsMap (or WeakMap)Object keys would become strings
Ordered list, duplicates allowedArrayIndexes, sorting, map/filter
Unique values, fast “is it there?”SetNo 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

  1. Using square brackets on a Map: map["pen"] = 5 sets an ordinary property, not a Map entry. Use map.set.
  2. Calling size() as a function; it is a property.
  3. Expecting JSON.stringify(map) to work; it gives {}. Convert with Object.fromEntries first.
  4. 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.

Next: JavaScript Regular Expressions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *