Map and Set in JavaScript

JavaScript

readTime

6 min

Map and Set in JavaScript

In JavaScript, there are many tools for storing data, such as classic objects and arrays. However, with the introduction of ECMAScript 6 (ES6), more flexible data structures like Map and Set became available, which can be a better choice for managing data.

This post will show you how to use these structures, as well as how to convert between them and other data types.

What is a Map in JavaScript?

A Map in JavaScript is a data structure that stores key-value pairs. Unlike traditional objects, a Map allows the use of any data type as a key, providing more flexibility compared to classic objects.

Creating a Map

To create a new map, use the constructor new Map():

js
const map = new Map();

This creates a new, empty map ready for use.

Adding Data to a Map

You can add data to a map using the set() method, which takes two arguments: a key and a value.

The key can be of any type – a number, string, or even an object.

js
const map = new Map();

map.set(1, "John");
map.set(2, "Maria");
map.set("animal", "Elephant");

In the example above, we create a map with three entries: the keys are numbers and a string.

Retrieving Data from a Map

To retrieve a value from the map, use the get() method:

js
console.log(map.get(1)); // John
console.log(map.get("animal")); // Elephant

Checking for Key Existence in a Map

You can check if a key exists in a map using the has() method:

js
console.log(map.has(2)); // true
console.log(map.has(10)); // false

Removing Elements from a Map

To remove an element from a map, use the delete() method and pass the relevant key:

js
map.delete(2);
console.log(map);

The code above removes key 2 from the map.

Iterating Over a Map

Maps can be iterated using a for...of loop or the forEach() method:

js
map.set(1, "John");
map.set(2, "Maria");
map.set("animal", "Elephant");

// Iterating with for...of
for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
}

// Iterating with forEach
map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

When to Use Maps?

Map is useful when you need a flexible data structure where keys can be of different types, including primitive values like numbers, strings, or objects. It also preserves the order of added elements, which may be crucial in some applications.

Additionally, unlike plain objects, Map handles frequent additions and deletions of elements more efficiently.

Set in JavaScript – A Collection of Unique Values

Set is another data structure in JavaScript that stores unique values, meaning duplicates cannot be added to a Set. It functions similarly to arrays but ensures each element is unique.

Creating a New Set

To create a Set, use the new Set() constructor:

js
const set = new Set();

Adding Data to a Set

You can add data to a Set using the add() method:

js
set.add(1);
set.add(2);
set.add(2); // Duplicate will be ignored
set.add(3);

console.log(set); // Set(3) {1, 2, 3}

Note that Set automatically eliminates duplicates.

Checking for Element Existence in a Set

To check if an element exists in a Set, use the has() method:

js
console.log(set.has(2)); // true
console.log(set.has(5)); // false

Removing Elements from a Set

To remove an element from a Set, use the delete() method:

js
set.delete(1);
console.log(set); // Set(2) {2, 3}

You can also remove all elements using the clear() method:

js
set.clear();
console.log(set); // Empty Set

Iterating Over a Set

You can iterate over elements in a Set using a for...of loop or the forEach() method:

js
set.add(1);
set.add(2);
set.add(3);

// Using for...of loop
for (const value of set) {
  console.log(value);
}

// Using forEach method
set.forEach((value) => {
  console.log(value);
});

When to Use Set?

Set is an excellent tool when you need to store unique values and want to eliminate duplicates. It can be used, for example, to filter data sets, ensuring each element appears only once.

WeakMap and WeakSet – Advanced Data Structures 🧠

WeakMap and WeakSet are special versions of Map and Set that store their keys (in the case of WeakMap) or values (in the case of WeakSet) as weak references. This means that if there are no other references to the key or value, they can be automatically removed by the Garbage Collector.

Creating WeakMap and WeakSet

To create a WeakMap or WeakSet, use the respective constructors:

js
const weakMap = new WeakMap();
const weakSet = new WeakSet();

When to Use WeakMap and WeakSet?

WeakMap and WeakSet are ideal for situations where you want to store references to objects but want the Garbage Collector to automatically manage their removal when they are no longer needed. A typical example could be storing user data in a graphical interface context where DOM elements may be dynamically removed.

Conversion Between Maps, Sets, and Other Collections

Array → Map Conversion

To convert an array to a Map, use the Map constructor and pass a two-dimensional array as an argument:

js
const arr = [
  [1, "John"],
  [2, "Maria"],
];
const map = new Map(arr);
console.log(map); // Map(2) { 1 => "John", 2 => "Maria" }

Map → Array Conversion

To convert a Map back to an array, use the Array.from() method:

js
const arrFromMap = Array.from(map);
console.log(arrFromMap); // [[1, 'John'], [2, 'Maria']]

Set → Array Conversion

Similarly, you can convert a Set to an array:

js
const set = new Set([1, 2, 3]);
const arrFromSet = Array.from(set);
console.log(arrFromSet); // [1, 2, 3]

Array → Set Conversion

Converting an array to a Set is just as simple:

js
const arr = [1, 1, 2, 3, 3];
const set = new Set(arr);

console.log(set); // Set(3) {1, 2, 3}

Interface and Implementation of Map and Set in JavaScript

It is worth noting that both Map and Set implement iterable interfaces, which means you can easily iterate over their elements using a for...of loop or other methods.

Both structures are part of modern interfaces in JavaScript that facilitate managing data collections.

Summary

Map and Set in JavaScript are data structures introduced in ES6 that offer flexible and efficient tools for working with data.

With the ability to use various data types as keys and eliminate duplicates, these data structures have a wide range of applications in everyday programming.

With additional features like WeakMap and WeakSet, we can better manage memory and references in complex applications.

Start using Map and Set in your projects to better organize and manage data more efficiently!

authorImg

Witek Pruchnicki

I passionately share knowledge about programming and more in various ways.