combine two maps in typescript

To combine two maps in TypeScript, one approach is to use the spread operator (...) or Object.assign method.

Let's say we have two maps, "map1" and "map2" with string keys and number values:

index.ts
let map1 = new Map<string, number>();
map1.set('a', 1);
map1.set('b', 2);

let map2 = new Map<string, number>();
map2.set('c', 3);
map2.set('d', 4);
149 chars
8 lines

To combine these two maps into a new map, we can use the spread operator as follows:

index.ts
let combinedMap = new Map<string, number>([...map1, ...map2]);
63 chars
2 lines

Or we can use the Object.assign method to create a new map and merge the two maps into it:

index.ts
let combinedMap = new Map<string, number>(Object.assign({}, map1, map2));
74 chars
2 lines

Either way, the resulting "combinedMap" will contain all the keys and their corresponding values from both "map1" and "map2".

gistlibby LogSnag