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 of 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.
The intersection will give us the elements that both arrays share in common.
let intersection = arr1.filter(x => arr2.includes(x));
The above implementation is not limited only to numbers. It can be applied to any data type as well.
let difference = arr1.filter(x => !arr2.includes(x));
The difference will output the elements from arr1
that are not in the arr2
.
If you would like to get the same output with Vanilla JS, the code below is what you will be using.
function difference(a1, a2) {
var result = [];
for (var i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
return result;
}
Compare this to two lines of code in ES7. Pretty useful, huh?
In this case, you’ll get an array containing all the elements of arr1
that are not in arr2
, and vice versa.
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
The union must be the simplest of them all. In the end, the result should be all the elements from A, all from B, or both.
We can simply use the JavaScript Spread operator to create a union.
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.
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()
— unionThat’s it for this article.
Happy coding! Thank you !
#javascript #EcmaScript #es7 #developer