1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
JavaScript's `Map` object provides an effective way to store key-value pairs. Iterating through a `Map` allows you to access and manipulate its entries. In this article, we explore various methods to iterate through a `Map` object, including the use of `forEach()`, `for...of` loops, and handling keys or values separately. Additionally, we’ll uncover a unique approach to iterating in reverse order.
Map.forEach()
The most straightforward way to traverse a Map
is by using the forEach()
method. This method executes a provided function once for each key-value pair, making it an efficient choice for iteration.
const exampleMap = new Map([
['city', 'Paris'],
['population', 2_138_551],
]);
exampleMap.forEach((value, key) => {
console.log(value, key);
});
The provided function receives the value and key as arguments, allowing you to perform operations within the loop.
An alternative to forEach() is the for…of loop, which directly iterates over the Map object. This approach uses destructuring assignment to capture both the key and value in each iteration, providing a concise and readable syntax.
const exampleMap = new Map([
['city', 'Paris'],
['population', 2_138_551],
]);
for (const [key, value] of exampleMap) {
console.log(key, value);
}
If you need to focus on either the keys or values of a Map, you can use the keys() or values() methods, respectively, and then iterate using a for…of loop.
These methods return iterator objects, allowing you to access either the keys or values with ease.
const exampleMap = new Map([
['city', 'Paris'],
['population', 2_138_551],
['landmark', 'Eiffel Tower'],
]);
for (const key of exampleMap.keys()) {
console.log(key);
}
for (const value of exampleMap.values()) {
console.log(value);
}
To iterate over a Map in reverse order, you can convert it to an array and then reverse the array using the reverse() method.
This technique involves converting the Map
to an array, reversing it, and then iterating through the reversed array using forEach()
.
const exampleMap = new Map([
['first', 1],
['second', 2],
]);
const reversedArr = [...exampleMap].reverse();
reversedArr.forEach(([key, value]) => {
console.log(key, value);
});
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Given a
Map
containing various values, write a functioncountDuplicates(map)
that counts and returns the number of duplicate values in theMap
. Use the knowledge gained from this article to implement the solution.
function countDuplicates(map) {
// > > > 👉 Write code here 👈 < < <
}
const sampleMap = new Map([
['a', 1],
['b', 2],
['c', 1],
['d', 3],
['e', 2],
]);
console.log(countDuplicates(sampleMap)); // Expected output👉: 2
Please attempt before seeing the Answer:
function countDuplicates(map) {
const valueCount = new Map();
map.forEach((value) => {
valueCount.set(value, (valueCount.get(value) || 0) + 1);
});
let duplicates = 0;
valueCount.forEach((count) => {
if (count > 1) {
duplicates += count - 1;
}
});
return duplicates;
}
Conclusion:
Effectively iterating through a Map object is a crucial skill for any JavaScript developer. Whether utilizing the simplicity of forEach(), the flexibility of for…of loops, or handling keys and values separately, understanding these methods provides a solid foundation for working with Map objects. Incorporate these techniques to manipulate and extract meaningful information from Map collections. Happy iterating! 🚀
Feel free to reach out!