Check if Two Arrays Intersect

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28165{{"`Check if Two Arrays Intersect`"}} javascript/data_types -.-> lab-28165{{"`Check if Two Arrays Intersect`"}} javascript/arith_ops -.-> lab-28165{{"`Check if Two Arrays Intersect`"}} javascript/comp_ops -.-> lab-28165{{"`Check if Two Arrays Intersect`"}} javascript/spread_rest -.-> lab-28165{{"`Check if Two Arrays Intersect`"}} end

How to Check if Two Arrays Have a Common Item

To check if two arrays have a common item, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Create a Set from b to get the unique values in b.
  3. Use Array.prototype.some() on a to check if any of its values are contained in b, using Set.prototype.has().
  4. Use the intersects function 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.

Other JavaScript Tutorials you may like