Introduction
In this lab, we will explore how to calculate the difference between two arrays without filtering duplicate values. The lab will guide you through the process of creating a Set from one array to get the unique values, and then using Array.prototype.filter() on the other array to keep only values that are not contained in the Set. By the end of the lab, you will have a better understanding of how to work with arrays in JavaScript.
Array Difference
To find the difference between two arrays, follow these steps:
Open the Terminal/SSH and type
nodeto start coding.Create a
Setfrom arraybto extract the unique values fromb.Use
Array.prototype.filter()on arrayato keep only the values that are not in arrayb, usingSet.prototype.has().
Here is the code:
const difference = (a, b) => {
const s = new Set(b);
return a.filter((x) => !s.has(x));
};
Example usage:
difference([1, 2, 3, 3], [1, 2, 4]); // Output: [3, 3]
Summary
Congratulations! You have completed the Array Difference lab. You can practice more labs in LabEx to improve your skills.