Home >Web Front-end >JS Tutorial >How to Check for Element Overlap Between a Target Array and Multiple Subarrays in JavaScript?

How to Check for Element Overlap Between a Target Array and Multiple Subarrays in JavaScript?

DDD
DDDOriginal
2024-12-30 15:17:09637browse

How to Check for Element Overlap Between a Target Array and Multiple Subarrays in JavaScript?

Verifying Element Overlap in Arrays Using JavaScript

Given an array of target elements targetArr and a series of other arrays subArr, determine whether any of the subarrays contain any element from the target array.

targetArr = ["apple", "banana", "orange"]
subArr = [
    ["apple", "grape"], // true
    ["apple", "banana", "pineapple"], // true
    ["grape", "pineapple"] // false
]

Vanilla JS Solution

const isElementPresent = (targetArr, subArr) => {
  return targetArr.some((element) => subArr.includes(element));
};

Explanation: The some method checks if any element in the subArr array passes the test provided by the callback function includes. If any element matches, it returns true; otherwise, it returns false.

// Example usage
const hasTargetElement = subArr.some((arr) => isElementPresent(targetArr, arr));

By iterating through each subarray using the some method, we can determine if any of the subarrays contain any element from the targetArr.

The above is the detailed content of How to Check for Element Overlap Between a Target Array and Multiple Subarrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn