JavaScript
Programming
Web Development
Array Manipulation
Coding Tips

How to get the difference between two arrays in JavaScript?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In JavaScript, finding the difference between two arrays – meaning identifying items present in one array but not in the other – is a common task akin to set operations in mathematics. This operation can be useful in various scenarios such as data processing, feature toggling, or simply comparing lists of values.

Understanding the Basics

The difference between two arrays can be one-sided (items in array A not in array B) or symmetrical (unique items in both arrays). It's important to note that JavaScript does not natively provide a direct method to achieve this, unlike some other programming languages that have built-in set operations. However, JavaScript's flexibility allows for efficient implementation using a combination of methods and newer language features.

Implementing One-Sided Difference

A one-sided difference between two arrays, say A and B, can be thought of as the relative complement of B in A (denoted as A\B). This includes all elements in A that are not in B. Here is how you can achieve it:

javascript
1const array1 = [1, 2, 3, 4, 5];
2const array2 = [4, 5, 6, 7];
3
4const difference = array1.filter(x => !array2.includes(x));
5console.log(difference); // Output: [1, 2, 3]

In this example, Array.prototype.filter is used to create a new array containing only those elements of array1 that do not appear in array2.

Implementing Symmetrical Difference

The symmetrical difference between two arrays includes all items that are unique to each array – items not found in both. Here's how you might implement this:

javascript
1const array1 = [1, 2, 3, 4, 5];
2const array2 = [4, 5, 6, 7];
3
4const difference = array1.filter(x => !array2.includes(x))
5    .concat(array2.filter(x => !array1.includes(x)));
6
7console.log(difference); // Output: [1, 2, 3, 6, 7]

This method involves using filter on both arrays and concatenating the results.

Optimizing for Larger Arrays

For larger arrays, using includes inside a filter method (which essentially leads to a time complexity of O(n*m)) may not be efficient. A more optimal approach may use Set, as shown below:

javascript
1const array1 = [1, 2, 3, 4, 5];
2const array2 = [4, 5, 6, 7];
3
4const setB = new Set(array2);
5const difference = array1.filter(x => !setB.has(x));
6
7console.log(difference);

Using a Set has an advantage since lookups (has method) are average O(1) time complexity, which greatly improves performance over using includes.

Different Methods for Different Use Cases

Different methods can be adopted depending on specific needs such as preserving duplicates, considering object arrays, or handling arrays with non-primitive types. For instance, comparing arrays of objects may require a JSON stringification approach or using a custom comparator function.

Summary Table

MethodBest forComplexity
Filter with IncludesSmall arrays, simplicityO(n*m)
Filter with SetLarger arrays, performance-sensitive scenariosO(n) for setup + O(1) average lookup
Custom Comparator FunctionArrays containing non-primitive typesVariable depending on function

Conclusion

Getting the difference between two arrays in JavaScript is a versatile operation, achievable through various methods tailored to specific circumstances and needs. Beginners might prefer the straightforwardness of using filter with includes, while more performance-sensitive applications may favour the Set method for significant efficiency improvements. Understanding these techniques not only helps tackle array comparisons but also deepens proficiency in JavaScript's array manipulation capabilities.

By mastering these concepts, developers can handle complex data transformations efficiently, making them invaluable in both web development and software engineering contexts.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.