Luhn's Algorithm - 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 don’t 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.

Hello!
“As you can see it’s doubling some of the digits, but not the odd ones.”

If you compare the two arrays it looks like that’s exactly what it is doing.
Double check what your if statement is actually checking,

2 Likes

Ah yes, it was doubling the odd digits and not the odd indexes. I changed reversed[0] for just i and it now works, thank you.

2 Likes

For the record: It should be noted in the narrative that this is NOT the Luhn Algorithm, but a variation on it. Just saying.