A Map is a collection that allows us to store key-value pairs, introduced in the ECMAScript 6 standard.
Unlike objects (Object
) (which also store key-value pairs), Map
offers several advantages in terms of performance and functionality. These are.
- Keys of any type, keys can be of any type (not just strings or symbols)
- Order, they maintain the insertion order.
- Size property, which indicates how many key-value pairs it contains.
- Easily iterable, we can easily iterate through its elements.
- Better performance, for insertion and deletion operations.
If you want to learn more about Maps (also called dictionaries)
check out the Introduction to Programming Course read more
Creating a Map
To create a Map
, we simply use the class constructor:
const map = new Map();
Here we have created an empty Map, ready to store key-value pairs.
We can also initialize a Map
with an iterable collection of key-value pairs:
const map = new Map([
['key1', 'value1'],
['key2', 'value2'],
[3, 'value3']
]);
Basic Usage of Map
Adding key-value pairs
To add elements to a Map
, we use the .set()
method:
const myMap = new Map();
// Adding keys and values
myMap.set("key1", "value1");
myMap.set(2, "value2");
myMap.set({ object: "key" }, "value3");
console.log(myMap);
// Map(3) { 'key1' => 'value1', 2 => 'value2', { object: 'key' } => 'value3' }
Each call to .set()
overwrites the value if the key already exists.
Accessing values
To get the value associated with a key, we use the .get()
method:
console.log(myMap.get("key1")); // 'value1'
console.log(myMap.get(2)); // 'value2'
// Using an object as a key
const objectKey = { object: "key" };
myMap.set(objectKey, "new value");
console.log(myMap.get(objectKey)); // 'new value'
Checking if a key exists
We can use the .has()
method to check if a key is present in the Map
:
console.log(myMap.has("key1")); // true
console.log(myMap.has("nonExistentKey")); // false
Removing elements
To remove a specific element, we use .delete()
:
myMap.delete(2);
console.log(myMap); // Map(2) { 'key1' => 'value1', { object: 'key' } => 'new value' }
To remove all elements, we use .clear()
:
myMap.clear();
console.log(myMap); // Map(0) {}
Iteration Methods
Map
offers several ways to iterate:
Using .forEach()
The .forEach()
method allows us to iterate over all key-value pairs in a Map
:
myMap.forEach((value, key) => {
console.log(`Key: ${key}, Value: ${value}`);
});
// Output:
// Key: a, Value: 1
// Key: b, Value: 2
// Key: c, Value: 3
Using a for...of
loop
We can also use a for...of
loop with the .entries()
, .keys()
, or .values()
methods:
// Iterate over entries
for (const [key, value] of myMap.entries()) {
console.log(`Key: ${key}, Value: ${value}`);
}
// Iterate over keys
for (const key of myMap.keys()) {
console.log(`Key: ${key}`);
}
// Iterate over values
for (const value of myMap.values()) {
console.log(`Value: ${value}`);
}
Practical Examples
Convert an array of objects to a dictionary
Suppose you have an array of objects with id
and name
, and you want to convert it into a dictionary where the id
is the key.
const people = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// Convert to a Map
const peopleMap = new Map(people.map(person => [person.id, person.name]));
console.log(peopleMap);
// Map(3) { 1 => 'Alice', 2 => 'Bob', 3 => 'Charlie' }
// Access a value by key
console.log(peopleMap.get(2)); // Bob
Count the occurrences of elements
Imagine we want to count how many times each word appears in a text:
const text = "maps maps in javascript are very useful";
const words = text.split(" ");
const counter = new Map();
words.forEach((word) => {
const frequency = counter.get(word) ?? 0;
counter.set(word, frequency + 1);
});
console.log(counter);
// Map(6) { 'maps' => 2, 'in' => 1, 'javascript' => 1, 'are' => 1, 'very' => 1, 'useful' => 1 }
Filter unique values from an array
You can use a Map
to filter duplicates based on a property of the objects.
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Alice' }, // Duplicate name
{ id: 4, name: 'Charlie' }
];
// Use Map to filter by name
const uniqueUsers = Array.from(
new Map(users.map(user => [user.name, user])).values()
);
console.log(uniqueUsers);
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob' },
// { id: 4, name: 'Charlie' }
// ]
Combine multiple maps into one
This example shows how to merge multiple maps into one.
const map1 = new Map([
[1, 'Alice'],
[2, 'Bob']
]);
const map2 = new Map([
[3, 'Charlie'],
[4, 'Diana']
]);
// Combine maps
const combinedMap = new Map([...map1, ...map2]);
console.log(combinedMap);
// Map(4) { 1 => 'Alice', 2 => 'Bob', 3 => 'Charlie', 4 => 'Diana' }