Hello! Day 2 working on this project, feeling like a dummy)) Here is what I have so far, I want to know if I am on a right track.
function validateCred(array){
let newArray = [];
for(let i = array.length - 1;i >= 0; i-=2){
let doubleValue = array[i] * 2
if(doubleValue < 9){
doubleValue =- 9;
}
newArray.push(doubleValue);
let sum = newArray.reduce((a, b)=> a + b, 0);
if(sum % 10 === 0){
return true;
}else{
return false;
};
}
1 Like
Did you copy the code to the forum correctly?
there is a missing }
to close your function. Also, I would loop over all the values first, adding them to new array
then after the loop, sum all the numbers once/one time. you currently sum every iteration of the loop
also, looking at this visual representation:
https://content.codecademy.com/PRO/independent-practice-projects/credit-card-checker/diagrams/cc%20validator%20diagram%201.svg
you can see we still need to all the numbers, so you can’t just skip every other number.
1 Like
Thank you for help!
Fixed the bracket. How could I miss it ! [facepalm]
I tried to look around how to avoid adding every other value to newArray. This is what I am doing atm :
function validateCred(array){
const newArray = [];
for(let i = array.length - 1;i >= 0; i--){
let doubleValue = array[i];
if((i % 2) === 0){
doubleValue *= 2;
}
if(doubleValue < 9){
doubleValue =- 9;
}
}
newArray.push(doubleValue);
let sum = newArray.reduce((a, b)=> a + b, 0)
if(sum % 10 === 0){
return true;
}else{
return false;
};
}
this line:
newArray.push(doubleValue);
should most certainly be in the loop. We want the loop to add the numbers to newArray
. Or you could simply do:
const total = 0;
for(let i = array.length - 1;i >= 0; i--){
let doubleValue = array[i];
if((i % 2) === 0){
doubleValue *= 2;
}
if(doubleValue < 9){
doubleValue =- 9;
}
total += doubleValue;
}
why use an array, while we can sum the values directly?
If you need more help, please also provide the exercise url