JavaScript: Reverse Key/Value of Map 🚀

By Xah Lee. Date: . Last updated: .

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

/* [
xah_inverse_map(xmap)
return a new map object that has key and val of xmap swapped.
URL: http://xahlee.info/js/js_map_reverse_key_val.html
Version 2020-04-21 2022-09-17
] */
const xah_inverse_map = ((xmap) => {
  const xm2 = new Map();
  xmap.forEach((vv, kk) => {
    xm2.set(vv, kk);
  });
  return xm2;
});

// ssss---------------------------------------------------

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

JavaScript Reverse Key/Value

JavaScript Map Object

BUY
ΣJS
JavaScript in Depth