Reverse an ES6 Map
10,731
Solution 1
How about new Map([...m].reverse());
?
let m = new Map([['a', 'apple'], ['b', 'banana']]);
let r = new Map([...m].reverse());
console.log([...m]);
console.log([...r]);
Solution 2
You can drop the .entries()
call as that's the default iterator of maps anyway:
new Map(Array.from(m).reverse())
Which actually seems both concise and straightforward to me - convert the map to a sequence, reverse that, convert back to a map.
Author by
Mikhail Batcer
Front end developer. Previously - full stack developer with Java, PHP, Python and SQL.
Updated on June 04, 2022Comments
-
Mikhail Batcer almost 2 years
Suppose I have created a Map object like this
Map {"a" => "apple", "b" => "banana"}
:m = new Map([ ["a", "apple"], ["b", "banana"] ]);
Now I want to reverse it and get
Map {"b" => "banana", "a" => "apple"}
I see the only way to do it as follows:
new Map(Array.from(m.entries()).reverse());
which doesn't look neither concise nor straightforward. Is there a nicer way?