CreditCard Checker Project

I´m way over my head on the first step of this project and is breaking my head.
After my First (failed) Attempt I decided to rework the code entirely. And ended up in this:

const validateCred = (arr) => {
  let nDigits = arr.length;
  let sum = arr.reverse();
  let parity = nDigits % 2;
  for (let i = 0; i <= sum.length; i++) {
    let j = sum.map(n => {
      if (sum[n] %2 === 0){
        n = n
      } else
        n = n *2
      if (n > 9) {
        n = n-9
      }
      return n
    })
    return j.reverse()
    }    
  }
console.log(validateCred(valid1))

The issue now is when the code finds a repeated number it breaks.
I. e const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; returns
[ 8, 5, 3, 9, 6, 7, 7, 9, 0, 7, 0, 1, 6, 7, 0, 7 ]
How do I fix this? I already have the snipped to reduce and test the ReducedArray%10 === 0, but this is the one thing not letting me move forward.
PLEASE HELP!
Thanks in advance

Hi,
it’s still the same issue:

You need to make a copy of the array.
Here is an overview of methods that mutate an array and those that don’t:

https://medium.com/@fknussel/arrays-objects-and-mutations-6b23348b54aa

I’m comfused.
I’m using .map now exactly because it creates a new array.
Or am I missing something?

You’re reversing the array before you map it. reverse() mutates the original array.

I´m scratching my head still.
Even after copyng the array backwards with

let sum = []
for (let k = 0; k <= arr.length; k++){
    sum.push(arr[k])
  }
//Returns [ 4, 1, 6, 9, 3, **5, 5,** 9, 0, 8, 0, 2, 3, 8, 0, 8, NaN ]

or


let sum = arr.slice().reverse()
//returns [ 4, 1, 6, 9, 3, **5, 5,** 9, 0, 8, 0, 2, 3, 8, 0, 8]

The output is till having trouble with the twin numbers.
Even iterating everyother number backwards withour modifying the array keeps returning either [7, 7] or the numbers * 2 -9 [5, 5]

You need to copy the array before you mutate it.
Then there is no need for the construction with sum.map inside the for loop, which is problematic. Consider pushing the digits to another array instead.

Here you want to process every other digit, right? But you’re checking if the value of the digit is even instead.

1 Like