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(mapObj)
return a new map object that has key and val of mapObj swapped.
2020-04-21
] */
const xah_inverse_map = ((mapObj) => {
 const m2 = new Map();
 mapObj.forEach ( ((vv,kk) => { m2.set(vv,kk) }) );
 return m2;
});

// 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

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc