Determining the Difference between Two Arrays in JavaScript
Introduction:
Determining the difference between two arrays is a common task in JavaScript. The difference can be defined as the elements that are present in one array but not in the other. This article provides several approaches to achieve this using JavaScript's built-in methods.
Intersection and Difference:
One approach is to use the Array.prototype.includes() method. It can be employed for both finding the intersection (common elements) and the difference between two arrays.
Intersection:
let intersection = arr1.filter(x => arr2.includes(x));
This filter produces an array containing the elements that are common to both arr1 and arr2.
Difference:
let difference = arr1.filter(x => !arr2.includes(x));
This filter creates an array with the elements that are present only in arr1, not in arr2.
Symmetric Difference:
Additionally, one may desire to determine the "exclusive or" (symmetric difference) between two arrays, which consists of unique elements from both arrays. This can be obtained by combining the difference of both arrays:
let symDifference = arr1.filter(x => !arr2.includes(x)) .concat(arr2.filter(x => !arr1.includes(x)));
Enhancement:
For improved usability, it is possible to define a custom method for Array.prototype that allows for direct usage on arrays:
Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }
With this enhancement, one can easily determine the difference:
[1, 2, 3].diff([2, 3]) // [1]
The above is the detailed content of How Can I Find the Difference Between Two Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!