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?
To use the map() method on an array in reverse order:Use the slice() method to get a copy of the array. Use the reverse() method to reverse the copied array. Call the map() method on the reversed array.
In-place Reversal Of Array In this method, the first element of the array is swapped with the last element of the array. Similarly, the second element of the array is swapped with the second last element of the array and so on. This way at the end of array traversal, we will have the entire array reversed.
reverse() is an inbuilt TypeScript function which is used to reverses the element of an array. Syntax: array. reverse();
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With