I’m working on the credit card checker project, and am stuck applying the luhn algorithm. I’ve successfully popped, and reversed the original string - and found the odd numbers, and multiplied them by 2. Now, I’m trying to take the numbers over 9 and subtract 9 while keeping them in the same string with the other numbers.
I’m not sure if this is the right direction to take - but I’ve been going around in circles for hours and need a nudge in the right direction.
Any help or thoughts would really be appreciated. Thank you!
My code is below:
function validateCred(array){ // remove last integer
array.pop(); //reverse the array
array.reverse(); //make new array with only odd index elements
const oddArray = ;
for(let i= 0; i < array.length; i++) {
if (i % 2 === 0) {
oddArray.push(array[i]);
}
} //take all results and multiply them by 2
var multiplyResult = oddArray.map(i => i*2) //TROUBLE SPOT
let calcResult = multiplyResult.map(i =>
{if (i>9) {
i=i-9
} else {
i=i
}
});
return calcResult
}; //used to check results in terminal
console.log(validateCred(valid1));
First, formatting your code will make it much easier for everyone to read, and provide assistance. See How do I format code in my posts?
Second, you are mutating the original array which will prove problematic later. Consider making a copy of the array, and performing your mutations on the copy. (Aside, is it really necessary to pop() the last integer from the array? You need to skip it when performing the doubling/subtracting 9 steps, but keep in mind that you still need the value added in to the final sum.)
Third, consider how you’ve written your callback function in your multiplyResult.map() call. You are using an anonymous arrow function. That’s fine, but don’t forget that you need to explicitly return the values that you want unless you want to implicitly returnundefined which will result in an array populated with undefined.
You are still mutating the original array (reversing it). There are a variety of ways to make a copy. One possibility is to use the slice() method. Also the code in your post is still not formatted. Please do format your code in future posts.