Use array.some()
The array.some() method checks if any element in one array exists in the other array.If any common element is found, it returns false
, indicating that the arrays are not disjoint. Otherwise, it returns true
.
Example: Implementation of program to find whether arrays are disjoint or not using Array.some() method
const disjoint = (a, b) => !a.some(e => b.includes(e));
const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
console.log("Are arrays disjoint:", disjoint(arr1, arr2));
Output
Are arrays disjoint: true
Time Complexity: O(n*m),where n is the length of arr1 and m is the length of arr2.
Auxiliary Space: O(1)
JavaScript Program to Find if Arrays are Disjoint or Not
Given two arrays, Our task is to check if the given two arrays are disjoint or not. Disjoint arrays in JavaScript are arrays that have no elements in common
Input: arr1[] = [12, 34, 11, 9, 3]
arr2[] = [2, 1, 3, 5]
Output: Not Disjoint
3 is common in two sets.
Input: arr1[] = [12, 34, 11, 9, 3]
arr2[] = [7, 2, 1, 5]
Output: Yes, Disjoint
There is no common element in two sets.
Table of Content
- Use array.some()
- Using Set
- Using Nested Loops