Why is this function not working? Why does it affect the result of my other function too?

Link to ‘Credit Card Checker’ project:

I am currently working on project requirement 4 in the ‘Credit Card Checker’ project which is to create the ‘findInvalidCards()’ function. After writing the code for the function and running the project I’ve noticed a couple of problems:

The first is that my ‘findInvalidCards()’ function is not working as intended and is returning an array of brand new number arrays unidentical to any of those in the array variable passed into the function (‘batch’) instead of just filtering out the valid credit card number arrays from ‘batch’. I have tried 2 different methods of writing the code for this function but both return the same result.

The second is that the function I created for project requirement 3 - ‘validateCred()’, is no longer returning the correct results despite doing so before. I know the cause of this is the ‘findInvalidCards()’ function because when I comment it out, the ‘validateCred()’ function goes back to returning the correct results. I can’t find the reason this is happening though.

The code I have written for the project is below:

// Add your functions below:
const validateCred = array => {
  let tempArray = array;
  for(let i = array.length - 2; i >= 0; i -= 2) {
    tempArray[i] *= 2;
    if(tempArray[i] > 9)
      tempArray[i] -= 9;
  let num = 0;
  tempArray.forEach(number => num += number);
  if((num % 10) === 0)
    return true;
  return false;

const findInvalidCards = array => {
  const invalidArray = array.filter(arr => validateCred(arr) === false);
  return invalidArray;

/* const findInvalidCards = array => {
  let invalidArray = [];
  for(let i = 0; i < array.length; i ++) {
    if(validateCred(array[i]) === false)
  return invalidArray;
} */



this line:

  let tempArray = array;

does not copy the array, you simply now have another variable which points to the same array in memory.

The original array being mutated causes your misery

1 Like