JS: Swap Key Value of Map 📜

By Xah Lee. Date: . Last updated: .

Here is a function that reverse the key-and-value of map object. That is, value become key, vice versa.

/*
xah_inverse_map(map_obj)
return a new map object that has key and val of map_obj swapped.
URL: http://xahlee.info/js/js_map_reverse_key_val.html
Created: 2019-05-21
Version: 2022-09-17
*/

const xah_inverse_map = (map_obj) => {
 const xout = new Map();
 map_obj.forEach((xval, xkey) => {
  xout.set(xval, xkey);
 });
 return xout;
};

// s------------------------------

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