DEV Community

Avnish
Avnish

Posted on

Check if Array contains any element of another Array in JS

Title : Check if Array contains any element of another Array in JS

You can achieve this in JavaScript using various methods such as includes(), some(), or indexOf(). I'll demonstrate how to use some() method to check if an array contains any element of another array.

Here's the code:

function containsAny(arr1, arr2) {
    return arr1.some(item => arr2.includes(item));
}

// Example arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [5, 6, 7, 8, 9];
const arr3 = [6, 7, 8, 9, 10];
const arr4 = [10, 11, 12, 13, 14];
const arr5 = [15, 16, 17, 18, 19];

// Examples
console.log(containsAny(arr1, arr2)); // Output: true
console.log(containsAny(arr1, arr3)); // Output: false
console.log(containsAny(arr1, arr4)); // Output: false
console.log(containsAny(arr1, arr5)); // Output: false
console.log(containsAny(arr2, arr3)); // Output: true
Enter fullscreen mode Exit fullscreen mode

Now, let's break down the code step by step:

  1. We define a function containsAny that takes two arrays arr1 and arr2 as parameters.
  2. Inside the function, we use the some() method on arr1. This method tests whether at least one element in the array passes the test implemented by the provided function.
  3. The provided function checks if each element (item) in arr1 is included in arr2 using the includes() method. If any element from arr1 is found in arr2, it returns true.
  4. If none of the elements from arr1 are found in arr2, some() returns false.
  5. We provide five examples (arr1 through arr5) and check if each of them contains any elements from another array (arr2 through arr4). We also provide an example where both arrays have no common elements (arr5 and arr1), hence it returns false as well.

Output:

  • true (arr1 contains 5 from arr2)
  • false (arr1 contains none of the elements from arr3)
  • false (arr1 contains none of the elements from arr4)
  • false (arr1 contains none of the elements from arr5)
  • true (arr2 contains 6 from arr3)

Top comments (0)