**Hi everyone, **
**I was wondering if any of you could help me figure out what I’m doing wrong in the Credit Card Checker exercise for the validateCred function. My output thus far is giving me each and every iteration of my loop, when I really only want the last one. Trouble is, I don’t know how to just get that one. **
This is my code (I’ve left out all the additional arrays and only included the one I’m testing with):
// All valid credit card numbers
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
// Add your functions below:
const validateCred = (array) => {
array.reverse();
const cardLength = array.length;
const checkDigit= array[0];
let newArray = [];
for (let i = 1; i < cardLength; i++) {
if (i % 2 === 0) {
newArray.push(array[i]);
}
else if (i % 2 !== 0) {
const odd = array[i] * 2;
if (odd > 9){
newArray.push(odd - 9);
}
else {
newArray.push(odd);
}
}
const x = newArray;
console.log(x);
const newArraySum = x.reduce((acc, val) => {
return acc + val;
});
totalSum = newArraySum + checkDigit;
console.log(totalSum);
/*if (totalSum % 10 === 0){
return true;
}
else {
return false;
}*/
}
}
validateCred (valid1);
The result I end up with is:
[ 0 ]
8
[ 0, 8 ]
16
[ 0, 8, 3 ]
19
[ 0, 8, 3, 1 ]
20
[ 0, 8, 3, 1, 0 ]
20
[ 0, 8, 3, 1, 0, 8 ]
28
[ 0, 8, 3, 1, 0, 8, 0 ]
28
[ 0, 8, 3, 1, 0, 8, 0, 9 ]
37
[ 0, 8, 3, 1, 0, 8, 0, 9, 5 ]
42
[ 0, 8, 3, 1, 0, 8, 0, 9, 5, 7 ]
49
[ 0, 8, 3, 1, 0, 8, 0, 9, 5, 7, 3 ]
52
[ 0, 8, 3, 1, 0, 8, 0, 9, 5, 7, 3, 9 ]
61
[ 0, 8, 3, 1, 0, 8, 0, 9, 5, 7, 3, 9, 6 ]
67
[ 0, 8, 3, 1, 0, 8, 0, 9, 5, 7, 3, 9, 6, 5 ]
72
[ 0, 8, 3, 1, 0, 8, 0, 9, 5, 7, 3, 9, 6, 5, 8 ]
80