How to find the intersection of two lists (values that exist in both lists) in TypeScript

3 Answers

0 votes
/**
 * Finds the unique intersection of two arrays (values present in both).
 * Preserves the relative order of elements as they first appear in the first array.
 *
 * @template T - The element type of the arrays.
 * @param {readonly T[]} first - The first input array.
 * @param {readonly T[]} second - The second input array.
 * @returns {T[]} Array containing unique common elements.
 *
 * Time Complexity:  O(n + m) where n and m are the lengths of the input arrays.
 * Space Complexity: O(m) to store the lookup Set.
 */
export function findArrayIntersection<T>(
  first: readonly T[],
  second: readonly T[]
): T[] {
  // 1. Load the second array into a Set for fast O(1) membership lookups
  const lookupSet: Set<T> = new Set<T>(second);

  // 2. Track processed matches to prevent duplicate values in the result
  const seenSet: Set<T> = new Set<T>();

  const result: T[] = [];

  // 3. Iterate through the first array to preserve original element ordering
  for (const item of first) {
    if (lookupSet.has(item) && !seenSet.has(item)) {
      result.push(item);
      seenSet.add(item);
    }
  }

  return result;
}

// --- Usage Example ---

const arr1: number[] = [5, 7, 1, 1, 3, 0, 6, 2];
const arr2: number[] = [2, 8, 8, 6, 9, 3, 3, 4, 4];

const intersection: number[] = findArrayIntersection(arr1, arr2);

console.log("Arr1:        ", arr1);
console.log("Arr2:        ", arr2);
console.log("Intersection:", intersection); // Output: [3, 6, 2]



/*
run:

Arr1:         [
  5, 7, 1, 1,
  3, 0, 6, 2
]
Arr2:         [
  2, 8, 8, 6, 9,
  3, 3, 4, 4
]
Intersection: [ 3, 6, 2 ]

*/

 



answered Sep 29 by avibootz
0 votes
// Explicitly type input arrays as number arrays
const arr1: number[] = [5, 7, 1, 1, 3, 0, 6, 2];
const arr2: number[] = [2, 8, 8, 6, 9, 3, 3, 4, 4];

// Direct conversion preserving your original array methods logic
const intersection: number[] = [...new Set(arr1)].filter((item: number) =>
  arr2.includes(item)
);

console.log(intersection);



/*
Run:

[ 3, 6, 2 ]

*/

 



answered Sep 29 by avibootz
0 votes
export function findArrayIntersection<T>(
    first: readonly T[],
    second: readonly T[]
  ): T[] {
   // Direct conversion preserving your original array methods logic
  const intersection: number[] = [...new Set(arr1)].filter((item: number) =>
    arr2.includes(item)
  );
   
  return intersection;
}
 
// --- Usage Example ---
 
const arr1: number[] = [5, 7, 1, 1, 3, 0, 6, 2];
const arr2: number[] = [2, 8, 8, 6, 9, 3, 3, 4, 4];
 
const intersection: number[] = findArrayIntersection(arr1, arr2);
 
console.log("Arr1:        ", arr1);
console.log("Arr2:        ", arr2);
console.log("Intersection:", intersection); // Output: [3, 6, 2]
 
 
 
/*
run:
 
Output:
Arr1:         [
  5, 7, 1, 1,
  3, 0, 6, 2
]
Arr2:         [
  2, 8, 8, 6, 9,
  3, 3, 4, 4
]
Intersection: [ 3, 6, 2 ]
 
*/
 

 



answered Sep 29 by avibootz
...