Invert a Map object
Given the assumption that there are no duplicate values, you can do an inverse like this:
const map: Map<string, number> = new Map();
map.set('3', 3);
map.set('4', 4);
const inverse: Map<number, string> = new Map();
map.forEach((value, key) => inverse.set(value, key));
You can use the spread operator on your original map to obtain key-value array pairs which you can .map
to swap each pair. Lastly, dump the result into the Map
constructor for your copy. Any duplicate keys will be lost.
const orig = new Map([["a",1],["b",2]]);
const cpy = new Map([...orig].map(e => e.reverse()));
console.log([...orig]);
console.log([...cpy]);
By the way, if your original values are indeed numbers and aren't sparse, consider using a plain old array for your "flipped" map. This might improve performance and semantics, entirely dependent on your use case.
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);