DEV Community

Vishesh Tiwari
Vishesh Tiwari

Posted 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">

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

Top comments (0)