Getting the Difference Between Two Arrays in JavaScript
Determining the difference between two arrays in JavaScript is a common requirement. This refers to identifying the elements that exist uniquely in one array but not in the other.
Using ES2016/ES7 Array.prototype.includes()
To achieve this, we can employ Array.prototype.includes(), introduced in ES2016/ES7. This method enables us to determine if an array contains a specific value.
Method to Get Difference
To calculate the difference between two arrays, where 'a1' and 'a2' are the input arrays, we can use the following code:
let difference = a1.filter(x => !a2.includes(x));
Explanation
The difference represents the values present only in 'a1' and not in 'a2'. The filter() method iterates over 'a1' and returns a new array containing elements that satisfy the given condition. The condition "!a2.includes(x)" checks if an element 'x' is not present in 'a2'. Thus, the resulting array 'difference' contains the elements of 'a1' that are absent in 'a2'.
Example
Consider the following example:
var a1 = ['a', 'b']; var a2 = ['a', 'b', 'c', 'd']; let difference = a1.filter(x => !a2.includes(x)); console.log(difference); // Output: ["c", "d"]
In this example, 'difference' will contain the elements "c" and "d", representing the values present in 'a2' but not in 'a1'.
The above is the detailed content of How Can I Find the Unique Elements in One JavaScript Array That Are Not Present in Another?. For more information, please follow other related articles on the PHP Chinese website!