Difference between first and the second array in JavaScript

When working with arrays in JavaScript, you often need to find elements that exist in one array but not in another. This operation is commonly known as finding the "difference" between two arrays.

We'll create a function that takes two arrays and returns all elements from the first array that don't exist in the second array.

Example

Here's how to implement this functionality:

const arr1 = ['1', '2', '3', '4/2', '5/4', '6-2'];
const arr2 = ['1', '2', '3', '5/4', '4/2', '6-1', '7/2', '8-2'];

const differenceBetween = (arr1 = [], arr2 = []) => {
    const res = [];
    for(let i = 0; i 

['6-2']

How It Works

The function iterates through each element in the first array and checks if it exists in the second array using the includes() method. If the element is not found in the second array, it's added to the result array.

Alternative Method: Using filter()

A more concise approach uses the filter() method:

const arr1 = ['apple', 'banana', 'cherry', 'date'];
const arr2 = ['banana', 'date', 'elderberry'];

const findDifference = (first, second) => {
    return first.filter(item => !second.includes(item));
};

console.log(findDifference(arr1, arr2));
['apple', 'cherry']

Comparison

Method Readability Performance Code Length
for loop with includes() Good O(n×m) More verbose
filter() with includes() Excellent O(n×m) Concise

Performance Considerations

For large arrays, consider using a Set for better performance:

const optimizedDifference = (arr1, arr2) => {
    const set2 = new Set(arr2);
    return arr1.filter(item => !set2.has(item));
};

const numbers1 = [1, 2, 3, 4, 5];
const numbers2 = [3, 4, 5, 6, 7];

console.log(optimizedDifference(numbers1, numbers2));
[1, 2]

Conclusion

Finding array differences is a common task in JavaScript. Use filter() with includes() for readability, or combine with Set for better performance with large datasets.

Updated on: 2026-03-15T23:19:00+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements