Home > OS >  JavaScript three array elements match-check by loops?
JavaScript three array elements match-check by loops?

Time:04-10

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.

CodePudding user response:

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');
  }
}

  • Related