Introduction
In this lab, we will be exploring an algorithm that determines whether two arrays have a common item or not. We will be using JavaScript and its built-in data structures to create a function that will take two arrays as input and return a boolean value indicating whether they intersect or not. This lab will help you improve your problem-solving skills and enhance your understanding of data structures and algorithms.
How to Check if Two Arrays Have a Common Item
To check if two arrays have a common item, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Create a
Setfrombto get the unique values inb. - Use
Array.prototype.some()onato check if any of its values are contained inb, usingSet.prototype.has(). - Use the
intersectsfunction provided below to test the arrays.
const intersects = (a, b) => {
const s = new Set(b);
return [...new Set(a)].some((x) => s.has(x));
};
Use the intersects function to check if two arrays intersect:
intersects(["a", "b"], ["b", "c"]); // true
intersects(["a", "b"], ["c", "d"]); // false
By following these steps and using the provided code, you can easily check if two arrays have a common item.
Summary
Congratulations! You have completed the Check if Two Arrays Intersect lab. You can practice more labs in LabEx to improve your skills.