skip to Main Content

I’m trying to pair elements of an array with the data of the other array in the same order and only once.

const num1 = [5, 10, 0, 1000, 6, 5]
const num2 = [6, 11, 0, -1000, 4, 5]

to be able to then loop through the arrays in a way that checks if

[5, 6] [10, 11] [0, 0] [1000, -1000] [6, 4] [5, 5]

this way

if num1 >= 5 || num2 >= 5 then console.log(true) if not console.log(false)

so far I have this

const num1 = [5, 10, 0, 1000, 6, 5]
const num2 = [6, 11, 0, -1000, 4, 5]
for (i = 0; i < num1.length; i++) {
    for (j = 0; j < num2.length; j++) {
    if ((num1[i] >= 5) && (num2[j] >= 5)) {
        console.log(true);
    } else {
        console.log(false)
    }
}
}

but it gives 12 results in the console instead of the expected 6
true
false
true
true
false
true

thank you for your time.

3

Answers


  1. const num1 = [5, 10, 0, 1000, 6, 5]
    const num2 = [6, 11, 0, -1000, 4, 5]
    
    for (i = 0; i < num1.length; i++) {
        if (num1[i] >= 5 && num2[i] >= 5) {
            console.log(true);
        } else {
            console.log(false)
        }
    }
    
    Login or Signup to reply.
  2. You can use forEach and make it code succinct as:

    const num1 = [5, 10, 0, 1000, 6, 5]
    const num2 = [6, 11, 0, -1000, 4, 5]
    
    num1.forEach((num, index) => console.log(num >= 5 && num2[index] >= 5))
    Login or Signup to reply.
  3. In your code you were performing a nested loop which means you were comparing each element. I have used a single loop to loop through both lists simultaneously.

    const num1 = [5, 10, 0, 1000, 6, 5]
    const num2 = [6, 11, 0, -1000, 4, 5]
    for (i = 0; i < num1.length; i++) {
        if ((num1[i] >= 5) || (num2[i] >= 5)) {
            console.log(true);
        } else {
            console.log(false)
        }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search