Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
JavaScript three array elements match-check by loops?

Unsure how to setup loops correctly to check whether elements in a targeted array matches any two other arrays or matches them both:

The code:

let test = [1,2,3,4,5,6,7]
let test2 = [7,8,9,10,11]
let check_test = [2,7,10,12]

for (var testa in test) {
  for (var test2a in test2) {
     for (var check_testa in check_test) {
        #Triple for-loop trying to loop all arrays
        if (check_testa == testa && check_testa != test2) {
           console.log("Match TEST")
        } else if (check_testa != testa && check_testa == test2) {
           console.log("Match TEST2")
        } else if (check_testa == testa && check_testa == test2) {
           console.log("Both match!")
        } else {
           console.log("None match!")
       }
     }
   }
 }

Basically the code supposed check whether the elements in array check_test matches any elements in the other two arrays test and test2.

If the element(of check_test) match elements in only one of the two other arrays, then print "Match [test] or [test2]!". If both match then print "Both Match!" and finally if both no match then print "None Match!"

And the output for this is supposed to be:

2 Match TEST!
7 Both Match!
10 Match TEST2!
12 None Match!

So how to set loops correctly to make it match-check then print the elements and output only once? Thanks for reading.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You don't need a nested loop. Use .includes to check which of the other arrays the value being iterated over exists in (if any), and don't use in when iterating over arrays (and if you were to use in, at least access the value in the array with bracket notation, rather than using the index only).

let test1 = [1,2,3,4,5,6,7];
let test2 = [7,8,9,10,11];
let check_test = [2,7,10,12];
for (const num of check_test) {
  const one = test1.includes(num);
  const two = test2.includes(num);
  if (one && two) {
    console.log('both');
  } else if (!one && !two) {
    console.log('neither');
  } else if (one) {
    console.log('one');
  } else {
    console.log('two');
  }
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!