Credit card checker: str.map() unreliably applying function?

Hi, I’m working on part 3 of this lesson, writing the validateCred(), and I cannot figure out why using .map() to double alternating credit card numbers works for only some numbers in the array. Here is my code:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];

function validateCred(arr) { 
  let valid = '';
  let arrSum = 0;
  let tempArrSum = 0;
  let tempArr = arr.slice(0, -1);
  console.log(arr);
  console.log(tempArr);
  tempArr.reverse();
  console.log(tempArr);

  tempArr = tempArr.map( 
    el => tempArr.indexOf(el) % 2 === 0 ? el : el * 2 
    );
  console.log(tempArr);

  tempArr = tempArr.map( 
    el => el <= 9 ? el : el - 9
  );
  console.log(tempArr);

  tempArr.forEach(el => tempArrSum += el);
  console.log(tempArrSum);

  arrSum = tempArrSum + (arr.slice(-1)[0]);
  console.log(arrSum);

  valid = arrSum % 10 === 0 ? true : false;
  return valid;
}
console.log(validateCred(valid1))

From the console.log()s, I can see that the array is sliced, reversed, the during the first .map() to double values, it goes from

[ 0, 8, 6, 1, 0, 8, 0, 9, 7, 7, 6, 9, 3, 5, 4 ]

to

[ 0, 16, 6, 2, 0, 16, 0, 18, 7, 7, 6, 18, 3, 10, 4 ]

What the heck? Why is it skipping the ‘7’ at index position 9? 9 modulo 2 is a clean 1, and the rest of the array is mapping correctly…

EDIT: midlindner pointed out that this is an unreliable means to retrieve index position of elements given duplicates in an array; calling map with it’s optional index argument lets you iteratively check modulo of the index position for each element in the conditional of the ternary expression.

What does the indexOf() method do? You are expecting it to do something that it does not do. For example, what would you expect the result below to be:

const nums = [1, 1, 1, 1, 1, 1, 1] for(let i = 0; i < nums.length; i++){ console.log(nums.indexOf(nums[i])); }

Check out the documentation for indexOf().

Aside, you should look up the map() method as well. You can optionally add a parameter for the index of each element.

1 Like