Subtracting array in JavaScript Delete all those elements from the first array that are also included in the second array

Subtracting arrays in JavaScript involves removing all elements from the first array that exist in the second array. This operation is useful for filtering data and finding differences between datasets.

Problem Statement

Given two arrays, we need to delete all elements from the first array that are also present in the second array.

const arr1 = ['uno', 'dos', 'tres', 'cuatro'];
const arr2 = ['dos', 'cuatro'];

// Expected output: ['uno', 'tres']

Using filter() with indexOf()

The filter() method creates a new array with elements that pass a test. We use indexOf() to check if an element exists in the second array.

const arr1 = ['uno', 'dos', 'tres', 'cuatro'];
const arr2 = ['dos', 'cuatro'];

const findSubtraction = (arr1 = [], arr2 = []) => {
    return arr1.filter(el => arr2.indexOf(el) === -1);
};

console.log(findSubtraction(arr1, arr2));
[ 'uno', 'tres' ]

Using filter() with includes() (Modern Approach)

The includes() method provides a cleaner syntax and better readability than indexOf().

const arr1 = ['uno', 'dos', 'tres', 'cuatro'];
const arr2 = ['dos', 'cuatro'];

const subtractArrays = (arr1, arr2) => {
    return arr1.filter(item => !arr2.includes(item));
};

console.log(subtractArrays(arr1, arr2));
[ 'uno', 'tres' ]

Using Set for Better Performance

For large arrays, using a Set improves performance as it has O(1) lookup time compared to O(n) for arrays.

const arr1 = ['uno', 'dos', 'tres', 'cuatro', 'cinco'];
const arr2 = ['dos', 'cuatro'];

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

console.log(subtractWithSet(arr1, arr2));
[ 'uno', 'tres', 'cinco' ]

Comparison of Methods

Method Readability Performance Browser Support
indexOf() Good O(n²) All browsers
includes() Excellent O(n²) ES2016+
Set Good O(n) ES2015+

Working with Numbers

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

const result = numbers1.filter(num => !numbers2.includes(num));
console.log(result);
[ 1, 3, 5 ]

Conclusion

Use filter() with includes() for most cases due to its readability. For large datasets, consider using Set for better performance. The filter() method creates a new array, leaving the original arrays unchanged.

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

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements