Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Merge Two Arrays and Remove Duplicate Items in JavaScript?
Next article icon

JavaScript – Check if Two Arrays are Disjoint

Last Updated : 17 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are some approaches to determine if two arrays share any common item in JavaScript

1. Using Loops – Simple

The simplest way to find common items is by using nested loops to compare each item in one array (a1) with every item in the second array (a2). This is great for smaller arrays, but less efficient for larger datasets.

JavaScript
const a1 = [1, 2, 3]; const a2 = [4, 5, 3];  let hasCommonItem = false; for (let i = 0; i < a1.length; i++) {     for (let j = 0; j < a2.length; j++) {         if (a1[i] === a2[j]) {             hasCommonItem = true;             break;         }     } }  console.log(hasCommonItem); 

Output
true 

3. Using Set and some() – Efficient

For larger arrays, converting one array (a2) into a Set and using some() to check items in a1 against the Set reduces time complexity as Set provides constant-time lookups.

JavaScript
const a1 = [1, 2, 3]; const a2 = [4, 5, 3];  const set = new Set(a2); const hasCommonItem = a1.some(item => set.has(item)); console.log(hasCommonItem); 

Output
true 

2. Using some() and includes()

The some() method, when combined with includes(), provides a more simpler way to check if any item in a1 exists in a2.

JavaScript
const a1 = [1, 2, 3]; const a2 = [4, 5, 3];  const hasCommonItem = a1.some(item => a2.includes(item)); console.log(hasCommonItem); 

Output
true 

4. Using filter() to Find Common Items

The filter() method can be used to get an array of items present in both a1 and a2. If the result has elements, then a1 and a2 share common items.

JavaScript
const a1 = [1, 2, 3]; const a2 = [4, 3, 5];  const commonItems = a1.filter(item => a2.includes(item)); console.log(commonItems); console.log(commonItems.length > 0);  

Output
[ 3 ] true 

5. Using Set Intersection

Creating a Set intersection is efficient when both arrays are converted into Sets. We then filter items from a1 that are in a2, resulting in the intersection of the two sets.

JavaScript
const a1 = [1, 2, 3]; const a2 = [3, 4, 5];  const intersection = new Set(a1.filter(item => new Set(a2).has(item))); console.log(intersection.size > 0); 

Output
true 

Importance of Finding Common Items Between Arrays

Finding common items between arrays is crucial for

  • Data Comparison: Quickly verifying overlaps between data lists.
  • Conditional Processing: Executing code based on shared elements.
  • Performance: Optimizing large data comparisons by choosing efficient methods like Set.


Next Article
How to Merge Two Arrays and Remove Duplicate Items in JavaScript?
author
anuupadhyay
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

  • JavaScript- Arrays are Equal or Not
    These are the following approaches to compare two arrays in JavaScript: 1. Using the JSON.stringify() MethodJavaScript provides a function JSON.stringify() method in order to convert an object whether or array into a JSON string. By converting it into JSON strings, we can directly check if the strin
    4 min read
  • Difference Between Two Arrays in JavaScript?
    These are the following ways to Get the Difference Between Two Arrays in JavaScript: 1. Using the filter() and includes() Methods - Mostly UsedWe can use the filter() method on the first array and check if each item is not present in the second array using the includes() method. The resulting array
    3 min read
  • How to Merge Two Arrays and Remove Duplicate Items in JavaScript?
    Given two arrays, the task is to merge both arrays and remove duplicate items from merged array in JavaScript. The basic method to merge two arrays without duplicate items is using spread operator and the set constructor. 1. Using Spread Operator and Set() ConstructorThe Spread Operator is used to m
    3 min read
  • Javascript Program for Find lost element from a duplicated array
    Given two arrays that are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element. Examples: Input: arr1[] = {1, 4, 5, 7, 9} arr2[] = {4, 5, 7, 9}Output: 11 is missing from second array.Input: arr1[] = {2, 3, 4, 5} arr2[
    4 min read
  • How to get symmetric difference between two arrays in JavaScript ?
    In this article, we will see how to get the symmetric difference between two arrays using JavaScript. In Mathematics the symmetric difference between two sets A and B is represented as A Δ B = (A - B) ∪ (B - A) It is defined as a set of all elements that are present in either set A or set B but not
    6 min read
  • JavaScript - Print Unique Elements From Two Unsorted Arrays
    Here are the different approaches to print unique elements from two unsorted arrays using JavaScript 1. Using filter() methodWe can filter all the unique elements using the filter() method. Then we will make one new array to concat our filtered array. [GFGTABS] JavaScript let a1 = [54, 71, 58, 95, 2
    2 min read
  • PHP | Find Intersection of two arrays
    You are given two arrays of n-elements each. You have to find all the common elements of both elements, without using any loop in php and print the resulting array of common elements. Example: Input : array1[] = {3, 5, 2, 7, 9}, array2[] = {4, 3, 2, 7, 8} Output : array ( [0] => 3, [1] => 2, [
    2 min read
  • How to Filter an Array from all Elements of another Array In JavaScript?
    Filtering one array from all elements of another array is a common task in JavaScript. This involves removing elements from one array that are present in another array. In this article we will explore different approaches to filter an array from all elements of another array in JavaScript. These are
    4 min read
  • How to find every element that exists in any of two given arrays once using JavaScript ?
    In this article, we will learn how to find every element that exists in any of the given two arrays. To find every element that exists in any of two given arrays, you can merge the arrays and remove any duplicate elements. Table of Content Using SetUsing loopUsing filter() and concat()Using reduce a
    3 min read
  • Javascript Program to Print uncommon elements from two sorted arrays
    Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50}Output : 10 25 40 50We do not print 20 and 30 as theseelements are p
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences