Question about credit card checker

Hi, I’ve managed to do #3 on credit card checker - hooray, didn’t think I could. But I have a question. In order to get it to do something to every other number working right to left, I’ve used ([i] % 2 === 0) but I guess this would only work if the number were always 16 digits long, for an odd-length number it would need to start with a modulo that isn’t equal to 0. How should I could I write it differently so that it works whatever length the number array is?

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


const validateCred = (array) => {
  let newArray = [];
  let lastDigit = array.pop()
  
  for(let i = array.length-1; i>=0; i--){  if([i] % 2 === 0) {
    if((array[i]*2) > 9) {newArray.push(array[i]*2-9)} else {
  newArray.push(array[i]*2)} } else
newArray.push(array[i]);}
const reducer = (accumulator, currentValue) => accumulator + currentValue;
let answer = newArray.reduce(reducer)+lastDigit;
if (answer % 10 === 0) {return `Credit Card number is valid`} else {return `Credit Card number is invalid`};
}
 

console.log(validateCred([6, 0, 1, 1, 1, 2, 7, 9, 6, 1, 7, 7, 7, 9, 3, 5]));

Hey nicolahearn

what does this conditional do?

([i] % 2 === 0)

I think I’m going to delete this. When I got to step 4 I found out that my code didn’t work properly :stuck_out_tongue_closed_eyes: All because I needed to answer the question I already asked about the card numbers being different lengths. Have figured it out now!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.