Reverse the Order of an ES6 Map in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Reverse the Order of an ES6 Map in JavaScript #

To reverse the order of a Map object:

  1. Use the Array.from() method to convert the Map to array.
  2. Call the reverse() method to reverse the array.
  3. Pass the result to the Map() constructor.
  4. The new Map will contain the elements in reverse order.
index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); const reversed = new Map(Array.from(map1).reverse()); console.log(reversed); // ๐Ÿ‘‰๏ธ {'two' => 2, 'one' => 1}

The first step is to use the Array.from method to convert the Map to an array of key-value pairs.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); const arr = Array.from(map1); console.log(arr); // ๐Ÿ‘‰๏ธ [['one', 1], ['two', 2]]

The first element in each sub-array is the key and the second - the value.

The next step is to use the Array.reverse method to reverse the array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); const arr = Array.from(map1); console.log(arr.reverse()); // ๐Ÿ‘‰๏ธ [['two', 2], ['one', 1] ]

The last step is to pass the reversed array as a parameter to the Map() constructor.

The Map() constructor takes an iterable object whose elements are key-value pairs, and uses them to create a new Map.

The new Map will contain the elements of the original Map in reverse order.

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

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); const reversed = new Map([...map1].reverse()); console.log(reversed); // ๐Ÿ‘‰๏ธ {'two' => 2, 'one' => 1}

We used the spread syntax (...) to unpack the key-value pairs of the Map into an array.

This achieves the same goal as the Array.from method.

In some rare scenarios the spread syntax (...) approach does not play nice with TypeScript. If you encounter those, use 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