6

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?

3
  • 6
    What exactly would you consider "nicer"? Maybe just put that code inside a function? function reverseMap(map) { ... }. Nobody has to know the ugly truth.... Commented Jun 1, 2016 at 14:37
  • 3
    If you care that much about the order of a map, I'd recommend to use an array in the first place. Maps actually are ordered only to be deterministic and consistent across engines, not that you order them manually.
    – Bergi
    Commented Jun 1, 2016 at 14:56
  • @Bergi I use Map, because I need unique keys: only one possible value in collection for each key. Commented Jun 1, 2016 at 20:12

2 Answers 2

11

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]);

2
11

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.

5
  • I didn't know maps guarantee an order. Is that something we should even rely upon?
    – Mulan
    Commented Jun 1, 2016 at 17:23
  • @naomik: Yes, maps (in contrast to objects) do have a determistic order, exactly to make things such as this predictable.
    – Bergi
    Commented Jun 1, 2016 at 18:04
  • @Bergi Just to clarify: Object.getOwnPropertyNames() doesn't produce a deterministic order in ES6? (sorry for being so pedantic)
    – user5536315
    Commented Jun 1, 2016 at 19:57
  • 1
    @Iven In fact Object.getOwnPropertyNames() does have predictable order, but for in enumerations do not.
    – Bergi
    Commented Jun 1, 2016 at 20:03
  • @user633183 In ES6 JavaScript, so-called maps guarantee order, that's what they are for there. But of course in e.g. Java or Python they generally do not (then again, there are seldom used implementations which maintain order in those languages too). Commented Jul 6, 2018 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.