How to go through an array skipping some indices?

Asked

Viewed 835 times

3

There’s a native way to do this?

for (var i in vetor) {
    for (var j in vetor) {
        if (i == j) {
            // pula o i
            break;
        }
    }
}

Is there any way to skip the i within the parentheses of the second for?

3 answers

10

Yes, there is. Just use continue. In this case, how do you want to interact with the loop external, you must specify a label and use it next to the continue. The label may be specified with an identifier before the for, followed by two points (:).

const vetor = [1, 2, 3, 4, 5];

loop_i: for (let i = 0; i < vetor.length; i++) {
    loop_j: for (let j = 0; j < vetor.length; j++) {
        if (i == j) continue loop_i;
        console.log("i:", i, "j:", j);
    }
}

Note that in the example the value of j is only travelled to the current value of i.

  • Did not know the existence of javascript Labels. Interesting :)

4

It must be something you wish for:

for (var i = 0; i < vetor.length; i++) {
    for (var j = 0; j < vetor.length; j++) {
        if (vetor[i] == vetor[j]) {
            i++;
            break;
        }
    }
}

I put in the Github for future reference.

Going through the vector through the index you have full control of how it is being incremented since it is a variable like any other.

  • actually I wanted to go through all positions of an array except the i position, do not go through to i.

  • 1

    just change the if to be if (vetor[i] == vetor[j])

  • 1

    I thought there was something more magical.

3

Complementing existing responses, depending on what you need, just reverse the logic.

Exchange the i == j for i != j and do what you need inside the if:

for (var i in vetor) {
    for (var j in vetor) {
        if (i != j) { 
            // Faz o que tem que fazer aqui, já vai pular o i == j naturalmente
        }
    }
}
  • 1

    You read my mind. Sopt moderators now have superpowers! P

  • 1

    @Augustovasques I only know the "superpowers" that come with the , but are far less than the people usually imagine kkkk.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.