2 min read

Set and Map

ES6 introduced two new data structures: Map and Set. These provide more robust ways to handle collections of data compared to plain Objects and Arrays.

1. Map

A Map holds key-value pairs where the keys can be any type (including objects, functions, or primitives).

Creating and Using a Map

const map = new Map();

map.set('name', 'John');
map.set(1, 'number one');
map.set(true, 'bool true');

console.log(map.get('name')); // "John"
console.log(map.get(1));      // "number one"
console.log(map.size);        // 3

Map vs. Object

Feature Map Object
Key Types Any type (Object, Function, etc.) Strings or Symbols
Key Order Insertion order is preserved Not guaranteed (though mostly insertion order in modern engines)
Size map.size property Manually calculate (e.g., Object.keys(obj).length)
Iteration Directly iterable Requires Object.keys() or for...in

Iteration

const recipeMap = new Map([
  ['cucumber', 500],
  ['tomatoes', 350],
  ['onion',    50]
]);

// Iterate over keys
for (let vegetable of recipeMap.keys()) {
  console.log(vegetable); // cucumber, tomatoes, onion
}

// Iterate over values
for (let amount of recipeMap.values()) {
  console.log(amount); // 500, 350, 50
}

// Iterate over entries [key, value]
for (let entry of recipeMap) { // same as recipeMap.entries()
  console.log(entry); // ['cucumber', 500] ...
}

2. Set

A Set is a collection of unique values. A value in the Set may only occur once.

Creating and Using a Set

const set = new Set();

set.add(1);
set.add(5);
set.add(5); // Duplicate is ignored
set.add('some text');

console.log(set.has(1)); // true
console.log(set.size);   // 3

Use Case: Removing Duplicates

The most common use case for a Set is to remove duplicates from an array.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Iteration

Sets are iterable, similar to Maps.

for (let value of set) {
  console.log(value);
}

// forEach is also supported
set.forEach((value) => {
  console.log(value);
});

programming/javascript/vanilla/javascript programming/javascript/vanilla/weakmap-and-weakset programming/javascript/vanilla/iterators-and-iterables