TypeScript Function to Find Common Elements in Two Arrays

Answered using ChatGPT 4o by ChatGPT4o

Question:

using typescript I want a function to return the element of one array if it existes on other array

Answer:

Certainly! You can create a TypeScript function that takes two arrays as input and returns the elements that exist in both arrays. Here's a simple implementation:

function findCommonElements<T>(array1: T[], array2: T[]): T[] {
    // Use a Set to store elements of the second array for quick lookup
    const set2 = new Set(array2);
    
    // Filter the first array to find elements that exist in the second array
    const commonElements = array1.filter(element => set2.has(element));
    
    return commonElements;
}

// Example usage:
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];

const common = findCommonElements(array1, array2);
console.log(common); // Output: [3, 4, 5]

Explanation:

  1. Generics (<T>): The function is generic, meaning it can work with arrays of any type.
  2. Set for Quick Lookup: A Set is used to store elements of the second array. This allows for O(1) average-time complexity for lookups.
  3. Filter Method: The filter method is used on the first array to find elements that exist in the Set created from the second array.

This function will return an array of elements that are present in both input arrays. If there are no common elements, it will return an