1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

How To Iterate Through A Map Object In JavaScript

ReadTime: 4 minutes

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.


Iterating with 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.

javascript
const exampleMap = new Map([
  ['city', 'Paris'],
  ['population', 2_138_551],
]);

exampleMap.forEach((value, key) => {
  console.log(value, key);
});
Map.forEach to iterate map

The provided function receives the value and key as arguments, allowing you to perform operations within the loop.


Using for…of Loop for Iteration

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.

javascript
const exampleMap = new Map([
  ['city', 'Paris'],
  ['population', 2_138_551],
]);

for (const [key, value] of exampleMap) {
  console.log(key, value);
}
for...of loop to iterate on Map

Iterating Over Keys or Values

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.

javascript
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);
}
Iterating on Map keys or values

Iterating in Reverse Order

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

javascript
const exampleMap = new Map([
  ['first', 1],
  ['second', 2],
]);

const reversedArr = [...exampleMap].reverse();

reversedArr.forEach(([key, value]) => {
  console.log(key, value);
});
Reverse iterate map

🧪Practice Coding Question: Count Duplicate Values

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Given a Map containing various values, write a function countDuplicates(map) that counts and returns the number of duplicate values in the Map. Use the knowledge gained from this article to implement the solution.

javascript
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
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
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;
}
Solution Code

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! 🚀

Contact

Feel free to reach out!