Iterate over a Map in Reverse Order in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 4, 2021

banner

Photo from Unsplash

Iterate over a Map in Reverse Order #

To iterate over a Map in reverse order:

  1. Use the Array.from() method to convert the Map to array.
  2. Use the reverse() method to reverse the array.
  3. Call the forEach method to iterate over the reversed array.
index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['two', 2], ['one', 1]] const reversedArr = Array.from(map1).reverse(); reversedArr.forEach(([key, value]) => { console.log(key, value); // 👉️ two 2, one 1 });

The first step is to convert the Map to an array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['one', 1], ['two', 2]] const arr = Array.from(map1);

Next, we use the Array.reverse method to reverse the array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['one', 1], ['two', 2]] const arr = Array.from(map1); // 👇️ [['two', 2], ['one', 1]] const reversed = arr.reverse();
The reverse() method reverses the array in place and returns the result.

Then, we can use the Array.forEach method to iterate over the reversed array.

The function we passed to the forEach method gets called with each element of the array.

We used destructuring assignment to assign the key and value variables.

index.js
const [key, value] = ['one', 1]; console.log(key); // 👉️ "one" console.log(value); // 👉️ 1

An alternative approach is to use the spread syntax (...) to convert the Map to an array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // 👇️ [['two', 2], ['one', 1]] const reversedArr = [...map1].reverse(); reversedArr.forEach(([key, value]) => { console.log(key, value); // 👉️ two 2, one 1 });

This code snippet achieves the same result, however this time we used the spread syntax (...) to unpack the key-value pairs of the Map into an array.

In some very rare cases, the spread syntax (...) doesn't play nice when using TypeScript. If you encounter those, opt for Array.from instead.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.