Sobes.tech
Junior

What is the intersection of arrays?

sobes.tech AI

Answer from AI

Array intersection is an operation that finds all elements common to two or more arrays. The result is a new array containing only these common elements. The order of elements in the resulting array may depend on the order in the original arrays, but often it does not matter.

For example, if we have two arrays arr1 = [1, 2, 3, 4] and arr2 = [3, 4, 5, 6], their intersection will be the array [3, 4].

There are several ways to implement array intersection in Node.js (and JavaScript in general):

  1. Using filter and includes:

    // arr1 = [1, 2, 3, 4];
    // arr2 = [3, 4, 5, 6];
    const intersection = arr1.filter(element => arr2.includes(element));
    // intersection will be [3, 4]
    

    This method is easy to understand but has suboptimal performance for large arrays because includes has a complexity of O(n) inside the filter loop.

  2. Using Set: Using Set is a more efficient way, especially for large arrays, as lookup in a Set has an average complexity of O(1).

    // arr1 = [1, 2, 3, 4];
    // arr2 = [3, 4, 5, 6];
    const set2 = new Set(arr2);
    const intersection = arr1.filter(element => set2.has(element));
    // intersection will be [3, 4]
    

    Or, if a unique set of elements is required:

    // arr1 = [1, 2, 2, 3, 4];
    // arr2 = [3, 4, 4, 5, 6];
    const set1 = new Set(arr1);
    const set2 = new Set(arr2);
    const intersectionSet = new Set([...set1].filter(element => set2.has(element)));
    const intersectionArray = Array.from(intersectionSet);
    // intersectionArray will be [3, 4]
    

The choice of method depends on the size of the arrays and performance requirements. For small arrays, the method with filter and includes is simple and understandable. For larger arrays, using Set is preferable.

What is the intersection of arrays? — Node.js - sobes.tech