find the intersection of two maps in typescript

To find the intersection of two maps in TypeScript we need to iterate over one of the maps and check if the key exists in the other map.

Here's an example function that takes two maps and returns their intersection as a new map:

index.ts
function intersection<K, V>(map1: Map<K, V>, map2: Map<K, V>): Map<K, V> {
  const resultMap = new Map<K, V>();

  // Iterate over the keys in map1
  for (const key of map1.keys()) {
    // Check if the key exists in map2
    if (map2.has(key)) {
      // If it does, add the key-value pair to the result map
      resultMap.set(key, map1.get(key)!);
    }
  }

  return resultMap;
}
384 chars
15 lines

Here we've defined a generic function that takes two maps of any key and value types. We create a new map that will hold the intersection, which we'll return at the end. We then iterate over the keys in the first map, and check if each key exists in the second map. If it does, we add the key-value pair to the result map.

Note that we're using the non-null assertion operator ! when getting the value from map1. This is safe since we know that map1 has the key since we're iterating over its keys.

We can then call this function with two maps of our choice to find their intersection:

index.ts
const map1 = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
]);
const map2 = new Map([
  ['b', 20],
  ['c', 30],
  ['d', 40],
]);

const intersectionMap = intersection(map1, map2);
console.log(intersectionMap); // Map { 'b' => 2, 'c' => 3 }
240 chars
14 lines

Here we're creating two maps containing some key-value pairs. We then call our intersection function passing both maps as arguments. The resulting map contains only the key-value pairs that are present in both maps, which is b: 2 and c: 3.

gistlibby LogSnag