Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert a Map object

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>
like image 898
pouya Avatar asked Jun 11 '19 19:06

pouya


People also ask

How do you invert an object in Javascript?

syntax. _. invert(object); This method takes an object as an argument and inverts it.


1 Answers

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);
like image 193
trincot Avatar answered Oct 03 '22 21:10

trincot