Home > Back-end >  Multiply by 9 every other element in an array
Multiply by 9 every other element in an array

Time:12-13

I have been thinking about this all day and decided to post my first question here.

I have an exercise in which basically I have to recreate Luhn algorithm to check credit cards.

These are the steps:

-Starting from the farthest digit to the right, AKA the check digit, iterate to the left.

-As you iterate to the left, every other digit is doubled (the check digit is not doubled). If the number is greater than 9 after doubling, subtract 9 from its value.

-Sum up all the digits in the credit card number.

-If the sum modulo 10 is 0 (if the sum divided by 10 has a remainder of 0) then the number is valid, otherwise, it’s invalid.


Create a function, validateCred() that has a parameter of an array. The purpose of validateCred() is to return true when an array contains digits of a valid credit card number and false when it is invalid. This function should NOT mutate the values of the original array.

so my code so far is :


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

const validateCred = array => {
  const newArr=[]
 

 for (let i= array.length - 1; i >= 0 ; i--){
   if (i % 2 === 0){
            newArr.push(array[i]);
    }else{
            newArr.push(array[i] * 2);
    }
    return newArr;
}
}

console.log(validateCred(valid1)) // this prints 16 only to the console 

so here I have returned all to the new array to check results, after iterating backwards I have tried to access every other number on valid1 but the output was 16, so I have accessed the 0 indexed element of the backwords array and not all the others. Which is incorrect.

CodePudding user response:

This is the precise implementation however the result is not returning the expected value based on the labelling of the input arrays. There must be something missing from the description of the algorithm steps.

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

function validateCred(array){
  var processed = [];
  var sumNumbers = 0;
  let reversedArray = array.reverse();
  var toggle = true;
  for (var i = 0; i < reversedArray.length; i  ) {
    let x = reversedArray[i];
    if (i!==0){
      if(toggle){
        x = x*2;
        if(x > 9){
          x = x - 9;
        }       
      }
    }
    processed.push(x);
    toggle = !toggle;
  }
  processed.forEach(function(item){
    sumNumbers = sumNumbers   item;
  });
  let result = sumNumbers % 10;
  if (result === 0) {
    return true;
  } else {
    return false;
  }
}

console.log(validateCred(valid1));
console.log(validateCred(invalid1));

CodePudding user response:

You can try to use map.

array.map(item => {
  if(item % 2 == 0){return item}
  else{return item * 9}
})
  • Related