find the union of two maps in typescript

To find the union of two maps in TypeScript, you can use the spread operator (...) to combine the entries of the two maps into a new map. Here's an example of how to do this:

index.ts
const map1 = new Map([['key1', 'value1'], ['key2', 'value2']]);
const map2 = new Map([['key2', 'updatedValue2'], ['key3', 'value3']]);

const unionMap = new Map([...map1, ...map2]);

console.log(unionMap); // prints Map(3) { 'key1' => 'value1', 'key2' => 'updatedValue2', 'key3' => 'value3' }
293 chars
7 lines

In the example above, we create two maps map1 and map2 and then use the spread operator (...) to combine their entries into a new map unionMap. The entries with common keys are overridden by the ones from map2.

This technique can be used to find the union of any number of maps, not just two. You can also use this approach to add new key-value pairs, as shown in the example with the 'key3' => 'value3' pair.

gistlibby LogSnag