Introduction
In this lab, we will explore how to find the symmetric difference between two arrays based on a provided function using JavaScript. We will use the Array.prototype.filter() and Array.prototype.findIndex() methods to compare the elements of the two arrays and return the values that are unique to each array. By the end of this lab, you will have a better understanding of how to use these methods to compare and manipulate arrays in JavaScript.
A Function to Find Array Symmetric Difference
To find symmetric difference between two arrays using a provided function as a comparator, follow these steps:
- Open Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.filter()andArray.prototype.findIndex()methods to find the appropriate values. - Use the given code to perform the operation.
const symmetricDifferenceWith = (arr, val, comp) => [
...arr.filter((a) => val.findIndex((b) => comp(a, b)) === -1),
...val.filter((a) => arr.findIndex((b) => comp(a, b)) === -1)
];
For example, consider the following input:
symmetricDifferenceWith(
[1, 1.2, 1.5, 3, 0],
[1.9, 3, 0, 3.9],
(a, b) => Math.round(a) === Math.round(b)
); // [1, 1.2, 3.9]
The above code will return [1, 1.2, 3.9] as the symmetric difference between the two arrays.
Summary
Congratulations! You have completed the Array Symmetric Difference Based on Function lab. You can practice more labs in LabEx to improve your skills.