Multiply by 9 every other element in an array

I have been thinking about this all day and decided to post my first question here.

I have an exercise in which basically I have to recreate Luhn algorithm to check credit cards.

These are the steps:

-Starting from the farthest digit to the right, AKA the check digit, iterate to the left.

-As you iterate to the left, every other digit is doubled (the check digit is not doubled). If the number is greater than 9 after doubling, subtract 9 from its value.

-Sum up all the digits in the credit card number.

-If the sum modulo 10 is 0 (if the sum divided by 10 has a remainder of 0) then the number is valid, otherwise, it’s invalid.


Create a function, validateCred() that has a parameter of an array. The purpose of validateCred() is to return true when an array contains digits of a valid credit card number and false when it is invalid. This function should NOT mutate the values of the original array.

so my code so far is :


const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];

const validateCred = array => {
  const newArr=[]
 

 for (let i= array.length - 1; i >= 0 ; i--){
   if (i % 2 === 0){
            newArr.push(array[i]);
    }else{
            newArr.push(array[i] * 2);
    }
    return newArr;
}
}

console.log(validateCred(valid1)) // this prints 16 only to the console 

so here I have returned all to the new array to check results, after iterating backwards I have tried to access every other number on valid1 but the output was 16, so I have accessed the 0 indexed element of the backwords array and not all the others. Which is incorrect.