Intersection of two arrays JavaScript

Finding the intersection of two arrays means finding elements that appear in both arrays, preserving the frequency of each element as it appears in both arrays.

For example, if we have arr1 = [1,2,3,1] and arr2 = [1,3,1], the intersection is [1,3,1] because element 1 appears twice in both arrays, and element 3 appears once in both.

Problem Statement

Given two arrays of numbers, we need to write a function that computes their intersection and returns an array containing the intersecting elements. Each element in the result should appear as many times as it shows in both arrays.

Input: arr1 = [1,2,3,1], arr2 = [1,3,1]
Output: [1,3,1]

Approach

Since the arrays are unsorted, we'll use a frequency-based approach. We iterate through the smaller array and check if each element exists in the larger array. When found, we add it to the result and remove it from the larger array to handle duplicates correctly.

arr1 = [1, 2, 43, 5, 3, 7] arr2 = [1, 6, 2, 7, 3, 5] Compare each element Intersection: [1, 2, 5, 3, 7]

Implementation

const arr1 = [1, 2, 43, 5, 3, 7, 7, 8, 4, 2];
const arr2 = [1, 1, 6, 6, 2, 78, 7, 2, 3, 7, 23, 5, 3];

const intersection = (arr1, arr2) => {
    const res = [];
    const { length: len1 } = arr1;
    const { length: len2 } = arr2;
    const smaller = (len1 = len2 ? arr1 : arr2).slice();
    
    for(let i = 0; i 

[1, 2, 5, 3, 7, 7, 2]

How It Works

The algorithm works by:

  • Identifying the smaller and larger arrays to optimize performance
  • Iterating through each element in the smaller array
  • Checking if the current element exists in the larger array using indexOf()
  • If found, adding the element to the result array
  • Replacing the found element with undefined to handle duplicates correctly

Alternative Approach Using Map

For better performance with large arrays, we can use a Map to track element frequencies:

const intersectionWithMap = (arr1, arr2) => {
    const map = new Map();
    const result = [];
    
    // Count frequencies in first array
    for(let num of arr1) {
        map.set(num, (map.get(num) || 0) + 1);
    }
    
    // Check second array and build intersection
    for(let num of arr2) {
        if(map.has(num) && map.get(num) > 0) {
            result.push(num);
            map.set(num, map.get(num) - 1);
        }
    }
    
    return result;
};

console.log(intersectionWithMap([1, 2, 2, 1], [2, 2]));
[2, 2]

Time Complexity Comparison

Method Time Complexity Space Complexity
indexOf() approach O(m × n) O(min(m,n))
Map approach O(m + n) O(min(m,n))

Conclusion

The intersection of two arrays can be found efficiently using frequency counting. The Map-based approach offers better performance for larger datasets, while the indexOf() method is simpler to understand for smaller arrays.

Updated on: 2026-03-15T23:18:59+05:30

722 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements