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
Now, let's break down the code step by step:
- We define a function
containsAnythat takes two arraysarr1andarr2as parameters. - Inside the function, we use the
some()method onarr1. This method tests whether at least one element in the array passes the test implemented by the provided function. - The provided function checks if each element (
item) inarr1is included inarr2using theincludes()method. If any element fromarr1is found inarr2, it returnstrue. - If none of the elements from
arr1are found inarr2,some()returnsfalse. - We provide five examples (
arr1througharr5) and check if each of them contains any elements from another array (arr2througharr4). We also provide an example where both arrays have no common elements (arr5andarr1), hence it returnsfalseas 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)