JS: Reverse Key Value of Map Obj

By Xah Lee. Date: .

Here's a function that reverse the key/value of map object.

That is, value become key, vice versa.

/* [
xah_swap_map_key_val(mapObj)
Return a new map object with key value of mapObj reversed.
That is, value become key, vice versa.
If values are not unique, the latter ones over rides previous as new map's key.
version 2019-05-21
 ] */
const xah_swap_map_key_val = ((mapObj) => {
 const m2 = new Map();
 mapObj.forEach ( ((vv,kk) => { m2.set(vv,kk) }) );
 return m2;
});

// test
console.log (
 xah_swap_map_key_val(new Map([[1,"a"], [2,"b"]]))
);
// Map { 'a' => 1, 'b' => 2 }

JS Map

  1. the Map Object Tutorial
  2. Iterate Over Map Object
  3. Convert Object to/from Map
  4. Map Filter
  5. Reverse Key/Value

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials