How to Determine if an Array Contains At Least Two Matching Items from Another Array in JavaScript

Looking for a JavaScript method to determine if an array includes at least two elements found in a different array. Example code below:

function verifyMatches(primaryList, secondaryList) {
  const totalMatches = primaryList.reduce((sum, element) => secondaryList.includes(element) ? sum + 1 : sum, 0);
  return totalMatches >= 2;
}

hey, u could try: primaryList.filter(i=>secondaryList.includes(i)).length>=2. it’s a pretty clean way to do it without extra loops, works well for me!

Based on my experience, using a loop that exits early when two matches are found can improve performance, especially with large arrays. This approach avoids processing unnecessary elements if the condition is met early on. For example, a traditional for loop can track matches and break out once two are encountered. This method is both clear and efficient. Running the check on each element ensures you don’t accidentally count duplicates or unnecessary items, making it a robust solution in various scenarios:

function verifyMatches(primaryList, secondaryList) {
  let count = 0;
  for (let i = 0; i < primaryList.length; i++) {
    if (secondaryList.includes(primaryList[i])) {
      count++;
      if (count === 2) return true;
    }
  }
  return false;
}