JavaScript Tutorial menu

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

javascript
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

MethodWhat 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
sizeHow 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

html
<!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 »
Output
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

javascript
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
Output
[ '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 size property and easy methods

Example

javascript
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");
MethodWhat 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
sizeNumber of pairs

Looping Through a Map

for...of gives each pair as [key, value], which you can destructure:

Example

html
<!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

javascript
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));
Output
{ 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?

UseWhen
ArrayAn ordered list, duplicates allowed
SetA list where every value must be unique
ObjectA fixed record with known string keys, like a student's details
MapKeys 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?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp