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
Release: 2024-12-30 15:17:09
Original
634 people have browsed it

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
]
Copy after login

Vanilla JS Solution

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

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));
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template