Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by Samantha Gades
To reverse the order of a Map
object:
Array.from()
method to convert the Map
to array.reverse()
method to reverse the array.Map()
constructor.Map
will contain the elements in reverse order.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.
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.
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.
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 (...).
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.
Array.from
instead.