DEV Community

Vishesh Tiwari
Vishesh Tiwari

Posted on • Edited on

How to reverse the key value pair in map ( typescript)?

In this article , we will learn how can we swap key with their value in map using custom typescript function.

Example

Here we have one colour map which having keys as OfferStatus enum and values as colour of badges.

enum OfferStatus {
  INPROGRESS='INPROGRESS',
  COMPLETE='COMPLETE',
  DEACTIVATE='DEACTIVATE',
  DELETED='DELETED'
}

type BadgeProps = {
  color: 'gold' | 'green' | 'neutral' | 'red';
};

const colourMap = new Map<OfferStatus, BadgeProps['color']>([
  [OfferStatus.INPROGRESS, 'gold'],
  [OfferStatus.COMPLETE, 'green'],
  [OfferStatus.DEACTIVATE, 'neutral'],
  [OfferStatus.DELETED, 'red'],
]);
Enter fullscreen mode Exit fullscreen mode

Now lets swap their values using below function -

function createReverseMap<K, V>(map: Map<K, V>): Map<V, K> {
  return new Map(Array.from(map, ([key, value]) => [value, key]));
}

const reverseColourMap = createReverseMap(colourMap);

console.log(Array.from(reverseColourMap.values()));
// output :  ["INPROGRESS", "COMPLETE", "DEACTIVATE", "DELETED"] 

console.log(Array.from(reverseColourMap.keys()));
// output :  ["INPROGRESS", "COMPLETE", "DEACTIVATE", "DELETED"] 
Enter fullscreen mode Exit fullscreen mode

values() method will return map iterator which is

MapIterator<OfferStatus> and keys() method will return map iterator which is

MapIterator<MapIterator<"gold" | "green" | "neutral" | "red">
Enter fullscreen mode Exit fullscreen mode

Then Array.from() expect iterator to construct the array.(Creates an array from an iterable object.)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay