Leonardo Saponara
Leonardo Saponara

Reputation: 5

How can I see in Javascript if the element of an array is in an odd or in an even position?

For my program, I've to double the numbers of the array in an odd position and then, if that number is over 9, subtract 9 to it. If I had to do it with odd numbers I could easily do it with the following code(Numero is the name of the array):

for (var k = 0; k < Numero.length;k++) {
    if ( (Numero[k] % 2) != 0) {
        var doppioNumero = Numero[k] * 2;
        Numero[k] = doppioNumero;
        if ( Numero[k] > 9) { 
            var nuovoNum = Numero[k] - 9; 
            Numero[k] = nuovoNum;
        }
    }
}

The problem is that I do NOT have to do it on odd numbers, I've to do it on numbers in odd positions, like the first number, the third, the fifth, the seventh, the ninth and so on. How can I do it? Thank you very much.

Upvotes: 0

Views: 125

Answers (4)

Joshua K
Joshua K

Reputation: 2537

You can use map instead of a for loop

Numero.forEach((v, k, arr)=>{
  if(k%2==1) arr[k]=arr[k]*2 % 9;
});

Upvotes: 0

Ammar
Ammar

Reputation: 820

for (var i = 0; i < Numero.length; i += 2) {
  Numero[i] = (Numero[i] * 2) % 9;
}

Upvotes: 0

Mitsakos
Mitsakos

Reputation: 244

To check for odd positions, you simply have to check the value of k (modulo) 2:

for (var k = 0; k < Numero.length;k++) {
    if ( k % 2) != 0) {
        var doppioNumero = Numero[k] * 2;
        Numero[k] = doppioNumero;
        if ( Numero[k] > 9) { 
            var nuovoNum = Numero[k] - 9; 
            Numero[k] = nuovoNum;
        }
    }
}

Upvotes: 0

marvel308
marvel308

Reputation: 10458

You can change your code to

for (var k = 0; k < Numero.length;k++) {
    if ( (k+1)&1) {
        var doppioNumero = Numero[k] * 2;
        Numero[k] = doppioNumero;
        if ( Numero[k] > 9) { 
            var nuovoNum = Numero[k] - 9; 
            Numero[k] = nuovoNum;
        }
    }
}

which would check at odd positions

Upvotes: 1

Related Questions