Home >Web Front-end >JS Tutorial >How Can I Efficiently Find the Intersection, Difference, and Symmetric Difference of Two JavaScript Arrays?
Finding Array Differences in JavaScript: Intersection, Difference, and Symmetric Difference
In JavaScript, comparing arrays element-by-element can be tedious. To simplify this process, let's explore a powerful tool: Array.prototype.includes().
Intersection
To obtain the values that are common to both arrays, we can use filter(). For instance:
let intersection = arr1.filter(x => arr2.includes(x));
This produces the intersection: [2, 3].
Difference
To identify values present only in arr1, we can filter out the elements that exist in arr2.
let difference = arr1.filter(x => !arr2.includes(x));
This results in the difference: [1].
Symmetric Difference
To get the elements found exclusively in either arr1 or arr2, we combine the two differences:
let symDifference = arr1.filter(x => !arr2.includes(x)) .concat(arr2.filter(x => !arr1.includes(x)));
This produces the symmetric difference: [1].
As highlighted by @Joshaven Potter, these methods can be added directly to the Array.prototype for enhanced flexibility:
Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }
Then, you can use it directly on arrays:
[1, 2, 3].diff([2, 3]) // [1]
The above is the detailed content of How Can I Efficiently Find the Intersection, Difference, and Symmetric Difference of Two JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!