Array Intersection, Difference, and Union with JavaScript ES7
An easier implementation than the indexOf method
Cover Photo by Bench Accounting on Unsplash
When you start working with actual projects, there might be instances where you will need to find elements present in one array and not present in another. This is basically the difference between the arrays. Likewise, you may need to find the union and intersection between two arrays as well.
In this piece, I'll explain how to get the above-intended output in the easiest way. We'll be using the Array.includes()
method from ES7 to achieve this.
Intersection (A ∩ B)
Illustration by Author
The intersection will return the elements shared by both arrays.
let intersection = arr1.filter(x => arr2.includes(x));
Code Snippet by Author
The above implementation is not limited only to numbers. It can be applied to any data type as well.
Code Snippet by Author
Difference (A - A ∩ B)
Illustration by Author
let difference = arr1.filter(x => !arr2.includes(x));
The above code snippet will output the elements from arr1
that are not in the arr2
.
Code Snippet by Author
If you would like to get the same output with Vanilla JS, the code below is what you will be using.
function difference(array1, array2) {
var result = [];
for (var i = 0; i < array1.length; i++) {
if (array2.indexOf(array1[i]) === -1) {
result.push(array1[i]);
}
}
return result;
}
Compare this to two lines of code in ES7. Pretty useful, huh?
Symmetric Difference (A + B - A ∩ B)
Illustration by Author
In this instance, you'll receive an array containing all the elements of arr1
that are not in arr2
and all the elements of arr2
that are not in arr1
.
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
Code Snippet by Author
Union (A∪B)
Illustration by Author
The union has to be the most basic of them all. The result should include all of the items from A, all of the items from B, or both.
We can simply use the JavaScript Spread operator to create a union.
Code Snippet by Author
If you note carefully, you'll see that some of the intersecting elements have been repeated in the above output. To avoid that, we should use the JavaScript Set Object. Why? Because Sets in JavaScript contain only distinct elements. For this reason, you won't have duplicates like above.
Code Snippet by Author
Issues and Complications
When you run the above implementations on arrays with a large number of elements, it becomes quite slow because it has O(n²) complexity. During these situations, you can use a JavaScript utility such as Lodash. This library has the best possible implementation for scenarios like this.
You should be using the functions below to achieve the above-intended outputs.
_.difference()
- difference_.xor()
- symmetric difference_.intersection()
- intersection_.union()
- union
Here is a small gift from me for reaching the end. Enjoy!
Code Pen by zoite
That's it for this article.
Happy coding!
Resources