# Collections

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Data Handling
Source: https://www.devtutorials.ai/learn/javascript/data-handling/collections

> Why Map and Set exist alongside objects and arrays, every Map and Set method, removing duplicates, converting between arrays, Sets, objects and Maps, and looping over collections with for...of and forEach().

## What Are Collections?

**Collection** = a value that holds a group of other values.

- **Array:** values in order, duplicates allowed.
- **Object:** named fields of one thing.
- **Map:** key → value lookups, where the key can be **any type**.
- **Set:** a list where each value appears **only once**.

**Simple lesson:** use a Map to look things up by key, and a Set to keep things unique.

### A Real-World Example

A shop stores stock by product id: `stock.get(101)` gives the count for product 101.
It also collects the cities it delivered to in a Set, so Chennai is counted once, however many orders went there.
Both jobs are clumsy with plain objects and arrays.

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="Left: a Map with number keys 101 and 102 pointing to values. Right: a Set where a second Chennai bounces off because it is already inside." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="40" y="34" fontSize="13" fill="#1e40af">Map</text>
    <rect x="40" y="48" width="70" height="34" rx="6" fill="#eff6ff" stroke="#2563eb" /><text x="75" y="70" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#1e40af">101</text>
    <rect x="150" y="48" width="100" height="34" rx="6" fill="#f0fdf4" stroke="#16a34a" /><text x="200" y="70" textAnchor="middle" fontSize="12" fill="#166534">12 in stock</text>
    <line x1="110" y1="65" x2="150" y2="65" stroke="#94a3b8" strokeWidth="2" />
    <rect x="40" y="96" width="70" height="34" rx="6" fill="#eff6ff" stroke="#2563eb" /><text x="75" y="118" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#1e40af">102</text>
    <rect x="150" y="96" width="100" height="34" rx="6" fill="#f0fdf4" stroke="#16a34a" /><text x="200" y="118" textAnchor="middle" fontSize="12" fill="#166534">0 in stock</text>
    <line x1="110" y1="113" x2="150" y2="113" stroke="#94a3b8" strokeWidth="2" />
    <text x="320" y="34" fontSize="13" fill="#854d0e">Set</text>
    <rect x="320" y="48" width="210" height="82" rx="10" fill="#fefce8" stroke="#ca8a04" />
    <text x="340" y="80" fontSize="12" fill="#854d0e">Chennai</text><text x="420" y="80" fontSize="12" fill="#854d0e">Pune</text><text x="340" y="112" fontSize="12" fill="#854d0e">Kochi</text>
    <text x="300" y="160" fontSize="12" fill="#dc2626">Chennai<animate attributeName="x" values="300;400;300" keyTimes="0;0.5;1" dur="2.5s" repeatCount="indefinite" /></text>
    <text x="440" y="165" fontSize="11" fill="#475569">already in: ignored</text>
  </svg>
  <figcaption>A Map links keys to values. A Set refuses a value it already has.</figcaption>
</figure>

The boxes print a Map as a list of `[key, value]` pairs, and a Set as a list of values. That is only the display.

## What You Will Learn

1. Why Map and Set exist, and when to pick each.
2. Map: `set`, `get`, `has`, `delete`, `clear`, `size`, `keys`, `values`, `entries`.
3. Set: `add`, `has`, `delete`, `clear`, `size`, `values`, and removing duplicates.
4. Converting between arrays, objects, Maps and Sets.
5. Looping over every kind of collection.

## Introduction to Collections

### Why collections are needed

- Object keys always become **strings**: the number `101` turns into `"101"`.
- Arrays keep **duplicates**: five visits by three people is five entries.

```js runnable title="An object turns number keys into strings, and an array keeps duplicates"
const stockById = {};
stockById[101] = "Desk Lamp";
console.log(Object.keys(stockById));
console.log(typeof Object.keys(stockById)[0]);

const visitors = ["Asha", "Ravi", "Asha", "Meera", "Ravi"];
console.log(visitors.length);
```

Expected output:

```text
[
  "101"
]
string
5
```

### Object vs Map vs Set

<div className="tscroll">

| | Object | Map | Set |
|---|---|---|---|
| Stores | named properties | key-value pairs | single values |
| Key types | strings (and symbols) | any type | no keys |
| Duplicates | one value per key | one value per key | each value once |
| Count | `Object.keys(o).length` | `map.size` | `set.size` |
| Best for | one record | lookups by data | uniqueness, "is it in?" |

</div>

## Map

A **Map** is like a phone's contact list: look up a key, get its value. It keeps keys in the order you added them.

### Creating a Map

`new Map()` is empty. `new Map([[key, value], ...])` starts with pairs.

```js runnable title="An empty Map, and a Map built from pairs"
const empty = new Map();
console.log(empty.size);

const prices = new Map([
  ["pen", 20],
  ["notebook", 65],
  ["marker", 45],
]);
console.log([...prices]);
```

Expected output:

```text
0
[
  [
    "pen",
    20
  ],
  [
    "notebook",
    65
  ],
  [
    "marker",
    45
  ]
]
```

### set()

`set(key, value)` adds a pair, or replaces the value if the key exists.

```js runnable title="set adds a pair, or replaces the value of an existing key"
const stock = new Map();

stock.set("pens", 120);
stock.set("notebooks", 45);
stock.set("pens", 110);
stock.set(101, "Desk Lamp");

console.log(Object.fromEntries(stock));
console.log(stock.size);
```

Expected output:

```text
{
  "101": "Desk Lamp",
  "pens": 110,
  "notebooks": 45
}
3
```

### get()

`get(key)` reads a value, or `undefined`. The key's **type** matters: `101` and `"101"` are different keys.

```js runnable title="get reads by key, and the key's type matters"
const products = new Map([
  [101, "Desk Lamp"],
  [102, "Wall Clock"],
]);

console.log(products.get(101));
console.log(products.get("101"));
console.log(products.get(999));
```

Expected output:

```text
Desk Lamp
undefined
undefined
```

### has()

`has(key)` asks "is this key here?" It is `true` even when the value is `0`.

```js runnable title="has checks for a key without reading its value"
const logins = new Map([
  ["asha@example.com", 3],
  ["ravi@example.com", 0],
]);

console.log(logins.has("ravi@example.com"));
console.log(logins.has("meera@example.com"));
console.log(logins.get("ravi@example.com"));
```

Expected output:

```text
true
false
0
```

### delete()

`delete(key)` removes one pair, and returns `true` if it was there.

```js runnable title="delete removes one pair"
const cart = new Map([
  ["pen", 2],
  ["notebook", 1],
  ["marker", 4],
]);

console.log(cart.delete("notebook"));
console.log(cart.delete("stapler"));
console.log([...cart.keys()]);
```

Expected output:

```text
true
false
[
  "pen",
  "marker"
]
```

### clear()

`clear()` removes every pair. The Map can be used again.

```js runnable title="clear empties the whole Map"
const cart = new Map([
  ["pen", 2],
  ["marker", 4],
]);

cart.clear();
console.log(cart.size);

cart.set("eraser", 1);
console.log([...cart]);
```

Expected output:

```text
0
[
  [
    "eraser",
    1
  ]
]
```

### size

`map.size` is the number of pairs. It is a property (no `()`), and there is no `length`.

```js runnable title="size is a property, and length does not exist"
const seats = new Map([
  ["A1", "Asha"],
  ["A2", "Ravi"],
  ["A3", "Meera"],
]);

console.log(seats.size);
console.log(seats.length);
```

Expected output:

```text
3
undefined
```

Always use `set()` and `get()`. `map["pens"] = 120` sets a plain property, so `map.size` stays `0`.

### keys()

All keys, in insertion order. It returns an **iterator** (hands out one item at a time), so spread it: `[...map.keys()]`.

```js runnable title="keys lists every key in insertion order"
const scores = new Map([
  ["Asha", 82],
  ["Ravi", 91],
  ["Meera", 76],
]);

console.log([...scores.keys()]);
```

Expected output:

```text
[
  "Asha",
  "Ravi",
  "Meera"
]
```

### values()

All values, in the same order. Spread them into an array to use array methods like `reduce()`.

```js runnable title="values lists every value, and the total follows"
const scores = new Map([
  ["Asha", 82],
  ["Ravi", 91],
  ["Meera", 76],
]);

const allScores = [...scores.values()];
console.log(allScores);
console.log(allScores.reduce((sum, score) => sum + score, 0));
```

Expected output:

```text
[
  82,
  91,
  76
]
249
```

### entries()

All pairs as `[key, value]` arrays. Position 0 is the key, position 1 the value.

```js runnable title="entries gives key and value together"
const scores = new Map([
  ["Asha", 82],
  ["Ravi", 91],
]);

const pairs = [...scores.entries()];
console.log(pairs[0]);
console.log(pairs[0][0], "scored", pairs[0][1]);
```

Expected output:

```text
[
  "Asha",
  82
]
Asha scored 82
```

### Iterating through a Map

`for (const [key, value] of map)` gives one pair per pass, unpacked into two names. The **Collection Iteration** section compares every loop.

```js runnable title="Looping over a Map gives one pair per pass"
const scores = new Map([
  ["Asha", 82],
  ["Ravi", 91],
  ["Meera", 76],
]);

for (const [name, score] of scores) {
  console.log(name + ": " + score);
}
```

Expected output:

```text
Asha: 82
Ravi: 91
Meera: 76
```

## Set

A **Set** is like a guest list at the door: a name is on it or not. Adding it twice changes nothing.

### Creating a Set

`new Set()` is empty. `new Set(array)` keeps one copy of each value.

```js runnable title="An empty Set, and a Set built from an array"
const empty = new Set();
console.log(empty.size);

const cities = new Set(["Chennai", "Pune", "Chennai", "Kochi"]);
console.log([...cities]);
```

Expected output:

```text
0
[
  "Chennai",
  "Pune",
  "Kochi"
]
```

### add()

`add(value)` puts a value in. A value already there is ignored, with no error.

```js runnable title="add ignores a value the Set already has"
const tags = new Set();

tags.add("sale");
tags.add("new");
tags.add("sale");

console.log([...tags]);
console.log(tags.size);
```

Expected output:

```text
[
  "sale",
  "new"
]
2
```

### has()

`has(value)` gives `true` or `false`. It is fast, even with thousands of values.

```js runnable title="has checks membership"
const allowed = new Set(["asha@example.com", "ravi@example.com"]);

console.log(allowed.has("ravi@example.com"));
console.log(allowed.has("meera@example.com"));
```

Expected output:

```text
true
false
```

### delete()

`delete(value)` removes one value, and returns `true` if it was there.

```js runnable title="delete removes one value"
const tags = new Set(["sale", "new", "limited"]);

console.log(tags.delete("new"));
console.log(tags.delete("clearance"));
console.log([...tags]);
```

Expected output:

```text
true
false
[
  "sale",
  "limited"
]
```

### clear()

`clear()` empties the Set.

```js runnable title="clear empties the whole Set"
const tags = new Set(["sale", "new"]);

tags.clear();
console.log(tags.size);
console.log(tags.has("sale"));
```

Expected output:

```text
0
false
```

### size

`set.size` counts the **unique** values. There is no `length`.

```js runnable title="size counts unique values only"
const answers = new Set(["yes", "no", "yes", "yes", "maybe"]);

console.log(answers.size);
console.log(answers.length);
```

Expected output:

```text
3
undefined
```

### Handling unique values

Remove duplicates from an array in one line: `[...new Set(array)]`.

```js runnable title="Remove duplicates in one line, and count the unique values"
const orderCities = ["Chennai", "Pune", "Chennai", "Kochi", "Pune", "Chennai"];

const uniqueCities = [...new Set(orderCities)];
console.log(uniqueCities);
console.log("Delivered to", uniqueCities.length, "cities");

const emails = ["Asha@Example.com", "asha@example.com"];
console.log(new Set(emails).size);
console.log(new Set(emails.map((email) => email.toLowerCase())).size);
```

Expected output:

```text
[
  "Chennai",
  "Pune",
  "Kochi"
]
Delivered to 3 cities
2
1
```

A Set removes only **exactly equal** values. `"Asha@x.com"` and `"asha@x.com"` are different, and so are two objects with the same contents.

### values()

All values in insertion order. `keys()` returns the same thing, so Sets and Maps can be used the same way.

```js runnable title="values lists everything in the Set"
const tags = new Set(["sale", "new", "limited"]);

console.log([...tags.values()]);
console.log([...tags.keys()]);
```

Expected output:

```text
[
  "sale",
  "new",
  "limited"
]
[
  "sale",
  "new",
  "limited"
]
```

### Iterating through a Set

`for (const value of set)` gives each unique value once.

```js runnable title="Looping over a Set gives one value per pass"
const attendees = new Set(["Asha", "Ravi", "Asha", "Meera"]);

for (const name of attendees) {
  console.log("Welcome, " + name);
}
```

Expected output:

```text
Welcome, Asha
Welcome, Ravi
Welcome, Meera
```

## Converting Between Collections

| From → To | How |
|---|---|
| Array → Set | `new Set(array)` |
| Set → Array | `[...set]` or `Array.from(set)` |
| Object → Map | `new Map(Object.entries(obj))` |
| Map → Object | `Object.fromEntries(map)` |

### Array to Set

```js runnable title="new Set turns an array into a Set"
const sizes = ["M", "L", "M", "S", "L"];
const sizeSet = new Set(sizes);

console.log(sizeSet.size);
console.log(sizeSet.has("S"));
```

Expected output:

```text
3
true
```

### Set to Array

A Set has no positions (`set[0]` is `undefined`), so convert it to read by position or sort.

```js runnable title="Spread or Array.from turns a Set back into an array"
const sizeSet = new Set(["M", "L", "S"]);

const withSpread = [...sizeSet];
const withFrom = Array.from(sizeSet);

console.log(withSpread);
console.log(withFrom.toSorted());
console.log(withSpread[0]);
```

Expected output:

```text
[
  "M",
  "L",
  "S"
]
[
  "L",
  "M",
  "S"
]
M
```

### Object to Map

`Object.entries()` gives `[key, value]` pairs, exactly what `new Map()` takes.

```js runnable title="Object.entries feeds new Map"
const stock = { pens: 120, notebooks: 45, markers: 30 };

const stockMap = new Map(Object.entries(stock));

console.log(stockMap.get("notebooks"));
console.log(stockMap.size);
```

Expected output:

```text
45
3
```

### Map to Object

`Object.fromEntries()` builds a plain object. Do this before saving as JSON; a Map has no JSON form.

```js runnable title="Object.fromEntries turns a Map into an object"
const stockMap = new Map([
  ["pens", 120],
  ["notebooks", 45],
]);

const stock = Object.fromEntries(stockMap);

console.log(stock);
console.log(stock.pens);
```

Expected output:

```text
{
  "pens": 120,
  "notebooks": 45
}
120
```

## Collection Iteration

### for...of

Works on arrays, Maps and Sets. You get an element, a `[key, value]` pair, or a value.

```js runnable title="One loop form, three collections"
const colours = ["red", "green"];
const codes = new Map([["red", "#ef4444"], ["green", "#16a34a"]]);
const picked = new Set(["green"]);

for (const colour of colours) console.log("array:", colour);
for (const pair of codes) console.log("map:", pair[0], pair[1]);
for (const colour of picked) console.log("set:", colour);
```

Expected output:

```text
array: red
array: green
map: red #ef4444
map: green #16a34a
set: green
```

### forEach()

Maps and Sets have `forEach()` too. On a Map, the **value comes first**, then the key.

```js runnable title="forEach on a Map gives the value first, then the key"
const codes = new Map([["red", "#ef4444"], ["green", "#16a34a"]]);
codes.forEach((value, key) => {
  console.log(key, "is", value);
});

const picked = new Set(["green", "blue"]);
picked.forEach((value) => {
  console.log("picked:", value);
});
```

Expected output:

```text
red is #ef4444
green is #16a34a
picked: green
picked: blue
```

`map.forEach((value, key) => ...)`. Writing `(key, value)` gives no error; the names are just swapped.

### Iterating Map entries

`for (const [name, line] of cart.entries())` is the clearest way to get both parts. `.entries()` is optional.

```js runnable title="Unpacking each Map entry to build a bill"
const cart = new Map([
  ["pen", { price: 20, qty: 3 }],
  ["notebook", { price: 65, qty: 2 }],
]);

let bill = 0;
for (const [item, line] of cart.entries()) {
  const cost = line.price * line.qty;
  console.log(item + ": " + cost);
  bill = bill + cost;
}
console.log("Bill:", bill);
```

Expected output:

```text
pen: 60
notebook: 130
Bill: 190
```

### Iterating Set values

Put repeats into a Set first, and each value is handled once.

```js runnable title="Send one reminder per customer, even when they ordered twice"
const orderEmails = ["asha@example.com", "ravi@example.com", "asha@example.com"];
const toRemind = new Set(orderEmails);

let sent = 0;
for (const email of toRemind.values()) {
  console.log("Reminder sent to " + email);
  sent = sent + 1;
}
console.log(sent, "reminders for", orderEmails.length, "orders");
```

Expected output:

```text
Reminder sent to asha@example.com
Reminder sent to ravi@example.com
2 reminders for 3 orders
```

## Collections on a Web Page

A Map holds the cart (product → quantity). A Set remembers which products were ever added. Press the buttons and watch both.

```js runnable preview="cart" title="A cart kept in a Map, with a Set of products seen"
const prices = new Map([["Notebook", 60], ["Steel bottle", 299], ["Pencil box", 120]]);
const cart = new Map();
const seen = new Set();

function draw() {
  const list = document.querySelector("#cart");
  list.innerHTML = "";
  let total = 0;
  for (const [name, qty] of cart) {
    const li = document.createElement("li");
    li.textContent = `${name} × ${qty}`;
    list.append(li);
    total += prices.get(name) * qty;
  }
  document.querySelector("#total").textContent = `₹${total}`;
  console.log(`cart.size = ${cart.size}, products ever added = ${seen.size}`);
}

for (const name of prices.keys()) {
  const li = document.createElement("li");
  const add = document.createElement("button");
  add.textContent = `Add ${name}`;
  add.addEventListener("click", () => {
    cart.set(name, (cart.get(name) ?? 0) + 1);
    seen.add(name);
    draw();
  });
  li.append(add);
  document.querySelector("#shop").append(li);
}

document.querySelector("#clear").addEventListener("click", () => {
  cart.clear();
  draw();
});
draw();
```

Add a notebook twice, then empty the cart. `cart.size` goes back to 0, but the Set still remembers the notebook.

**Easy way to remember:** **Map** = a dictionary (word → meaning). **Set** = a guest list (in or out, once).

## TL;DR

- Map: any-type keys, `set`/`get`/`has`/`delete`, `size`, insertion order.
- Set: unique values, `add`/`has`/`delete`, `size`; `[...new Set(arr)]` removes duplicates.
- Both use `size`, not `length`, and loop with `for...of`.
- Convert with `new Set()`, `[...set]`, `new Map(Object.entries())`, `Object.fromEntries()`.
- `map.forEach((value, key) => ...)`: value first.

## Try this

In **Iterating through a Map**, add `scores.set("Ravi", 95);` before the loop. It still prints three lines, and Ravi stays second with 95: `set()` on an existing key replaces the value in place.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `map[key] = value` | Brackets add entries | Use `map.set(key, value)` | `size` stays 0, `get()` misses |
| `map.length` | Collections have `length` | Use `size` | `undefined` |
| `map.get("101")` for key `101` | Keys are converted | Types must match | `undefined` |
| `map.forEach((key, value) => ...)` | Key comes first | Value comes first | Names are swapped |
| Duplicates left in a Set | Similar values merge | Only exact matches merge | Case or object copies stay |
| `set[0]` | Sets have positions | Use `[...set][0]` | `undefined` |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `new Map()` or `new Map([[key, value]])` | create an empty Map, or one filled from pairs |
| `map.set(key, value)` | add a pair, or replace the value of an existing key |
| `map.get(key)` | read the value, or `undefined` if the key is missing |
| `map.has(key)` / `map.delete(key)` / `map.clear()` | check for a key, remove one key, remove every key |
| `map.keys()` / `map.values()` / `map.entries()` | every key, every value, every `[key, value]` pair |
| `new Set()` or `new Set(array)` | create an empty Set, or one filled from an array |
| `set.add(value)` | add a value, ignored if it is already there |
| `set.has(value)` / `set.delete(value)` / `set.clear()` | check for a value, remove one value, remove every value |
| `map.size` / `set.size` | how many entries or values |
| `[...new Set(array)]` | an array with duplicates removed |
| `new Map(Object.entries(obj))` | object to Map |
| `Object.fromEntries(map)` | Map to object |
| `for (const [key, value] of map)` | loop over Map entries |
| `map.forEach((value, key) => …)` | loop over a Map, value first |

</div>

## Exercises

## What to Remember

- Map for lookups by any key; Set for unique values.
- `size`, not `length`. `set()`/`get()`, not brackets.
- Converting is one line in each direction.

Next: **JSON Handling**. Turn data into JSON text and back, see what JSON cannot carry, and handle JSON errors safely.
