Finding the difference between two arrays - JavaScript

Finding the difference between two arrays means identifying elements that exist in one array but not in the other. This is a common operation when comparing datasets or finding unique values.

We have two arrays of numbers like these:

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

We need to write a JavaScript function that takes in two such arrays and returns the elements that are not common to both arrays.

Using indexOf() Method

The traditional approach uses nested loops with indexOf() to check if elements exist in the other array:

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

const difference = (first, second) => {
    const res = [];
    for(let i = 0; i 

[ 6, 5, 1 ]

Using filter() and includes() Methods

A more modern and concise approach using array methods:

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

const findDifference = (first, second) => {
    const diff1 = first.filter(x => !second.includes(x));
    const diff2 = second.filter(x => !first.includes(x));
    return [...diff1, ...diff2];
};

console.log(findDifference(arr1, arr2));
[ 6, 5, 1 ]

Using Set for Better Performance

For larger arrays, using Set provides better performance as lookups are O(1):

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

const findDifferenceWithSet = (first, second) => {
    const set1 = new Set(first);
    const set2 = new Set(second);
    
    const diff1 = first.filter(x => !set2.has(x));
    const diff2 = second.filter(x => !set1.has(x));
    
    return [...diff1, ...diff2];
};

console.log(findDifferenceWithSet(arr1, arr2));
[ 6, 5, 1 ]

Comparison

Method Time Complexity Readability Best For
indexOf() loops O(n²) Medium Small arrays
filter() + includes() O(n²) High Small to medium arrays
Set approach O(n) High Large arrays

Conclusion

For finding array differences, use filter() with includes() for readability or Set-based approach for better performance with large datasets. The choice depends on your specific use case and array sizes.

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

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements