I was wondering, what is the most convenient way to invert keys and values in a Map. Is there any builtin method or should it be done by iterating over keys and values?
const map: Map<string, number> = new Map()
const inverse: Map<number, string>
syntax. _. invert(object); This method takes an object as an argument and inverts it.
You could pass the inverse tuples to the constructor, using Array.from
and Array#reverse
:
new Map(Array.from(origMap, a => a.reverse()))
See it run on an example:
const origMap = new Map([[1, "a"],[2, "b"]]);
console.log(...origMap);
// Reverse:
const inv = new Map(Array.from(origMap, a => a.reverse()));
console.log(...inv);
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