Reputation: 2065
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?
Upvotes: 6
Views: 13846
Reputation: 51957
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]);
Upvotes: 11
Reputation: 665456
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.
Upvotes: 11