Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse an ES6 Map

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?

like image 577
Mikhail Batcer Avatar asked Jun 01 '16 14:06

Mikhail Batcer


People also ask

How do you reverse a map order?

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.

How do you reverse an array in place?

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.

How do you reverse a list in TypeScript?

reverse() is an inbuilt TypeScript function which is used to reverses the element of an array. Syntax: array. reverse();


2 Answers

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.

like image 170
Bergi Avatar answered Nov 06 '22 01:11

Bergi


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]);
like image 37
Patrick Roberts Avatar answered Nov 06 '22 02:11

Patrick Roberts