JavaScript: Reverse Key/Value of Map

By Xah Lee. Date: . Last updated: .

Here's 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

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc