Iterate over a Map in Reverse Order in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee