Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
Why is my code not doubling every odd index?

I'm trying to write a version of Luhn's algorithm, but why is my code not doubling every odd index here? It seems to be doubling a pattern of index's but i dont understand how it's got that pattern from my code.

    const validateCred = (array) => {
      let removeLast = array.pop();
      let reversed = array.reverse();
      console.log(reversed);
      for (let i = reversed[0]; i < reversed.length; i++)
      if (reversed[i] % 2 !== 0) {
        reversed[i] *= 2;
      }
      console.log(reversed)




[ 0, 8, 6, 1, 0, 8, 0, 9, 7, 7, 6, 9, 3, 5, 4 ]
[ 0, 8, 6, 2, 0, 8, 0, 18, 14, 14, 6, 18, 6, 10, 4 ]

As you can see it's doubling some of the digits, but not the odd ones.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you are talking about odd indexes, the problem you use reversed[i] in the "for" loop, and later in the "if" condition. Replaced both instances by just "i". The "i" represents the index in this code.

Fixed function:

const validateCred = (array) => {
          let removeLast = array.pop();
          let reversed = array.reverse();
          console.log(reversed);
          for (let i = 0 ; i < reversed.length; i++)
          if (i % 2 !== 0) {
            reversed[i] *= 2;
          }
     
          console.log(reversed)
     }

If you are about doubling every odd element in the array, this will work - keep "i" at the loop and reversed[i] at the "if":

const validateCred = (array) => {
      let removeLast = array.pop();
      let reversed = array.reverse();
      console.log(reversed);
      for (let i = 0; i < reversed.length; i++)
      if (reversed[i] % 2 !== 0) {
        reversed[i] *= 2;
      }
 
      console.log(reversed)
 }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda