Collections in JavaScript

By Syncfusion®, Inc. · Last updated

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.

Map 101 12 in stock

102 0 in stock

Set

ChennaiPuneKochi Chennai already in: ignored

A Map links keys to values. A Set refuses a value it already has.

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.

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:

[
  "101"
]
string
5

Object vs Map vs Set

ObjectMapSet
Storesnamed propertieskey-value pairssingle values
Key typesstrings (and symbols)any typeno keys
Duplicatesone value per keyone value per keyeach value once
CountObject.keys(o).lengthmap.sizeset.size
Best forone recordlookups by datauniqueness, "is it in?"

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.

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:

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

set()

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

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:

{
  "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.

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:

Desk Lamp
undefined
undefined

has()

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

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:

true
false
0

delete()

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

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:

true
false
[
  "pen",
  "marker"
]

clear()

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

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:

0
[
  [
    "eraser",
    1
  ]
]

size

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

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:

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()].

keys lists every key in insertion order

const scores = new Map([
  ["Asha", 82],
  ["Ravi", 91],
  ["Meera", 76],
]);

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

Expected output:

[
  "Asha",
  "Ravi",
  "Meera"
]

values()

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

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:

[
  82,
  91,
  76
]
249

entries()

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

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:

[
  "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.

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:

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.

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:

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

add()

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

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:

[
  "sale",
  "new"
]
2

has()

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

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:

true
false

delete()

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

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:

true
false
[
  "sale",
  "limited"
]

clear()

clear() empties the Set.

clear empties the whole Set

const tags = new Set(["sale", "new"]);

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

Expected output:

0
false

size

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

size counts unique values only

const answers = new Set(["yes", "no", "yes", "yes", "maybe"]);

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

Expected output:

3
undefined

Handling unique values

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

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:

[
  "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.

values lists everything in the Set

const tags = new Set(["sale", "new", "limited"]);

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

Expected output:

[
  "sale",
  "new",
  "limited"
]
[
  "sale",
  "new",
  "limited"
]

Iterating through a Set

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

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:

Welcome, Asha
Welcome, Ravi
Welcome, Meera

Converting Between Collections

From → ToHow
Array → Setnew Set(array)
Set → Array[...set] or Array.from(set)
Object → Mapnew Map(Object.entries(obj))
Map → ObjectObject.fromEntries(map)

Array to Set

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:

3
true

Set to Array

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

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:

[
  "M",
  "L",
  "S"
]
[
  "L",
  "M",
  "S"
]
M

Object to Map

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

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:

45
3

Map to Object

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

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:

{
  "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.

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:

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.

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:

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.

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:

pen: 60
notebook: 130
Bill: 190

Iterating Set values

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

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:

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
map[key] = valueBrackets add entriesUse map.set(key, value)size stays 0, get() misses
map.lengthCollections have lengthUse sizeundefined
map.get("101") for key 101Keys are convertedTypes must matchundefined
map.forEach((key, value) => ...)Key comes firstValue comes firstNames are swapped
Duplicates left in a SetSimilar values mergeOnly exact matches mergeCase or object copies stay
set[0]Sets have positionsUse [...set][0]undefined

Quick reference

SyntaxMeaning
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.sizehow 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

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.