Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array.map is not a function even though I have it typed correctly

I am wondering why I’m getting this error message? But array.map is correct in how I’m stating it?

/home/ccuser/workspace/credit-card-checker/main.js:40
newArr = array.map((element, index) => index % 2 === 1 ? element * 2 : element);
^

TypeError: array.map is not a function
at validateCred

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

const validateCred = (array) => {
  let newArr = [];
  let newestArr = [];
  let reducedResult = 0;
  const reducer = (previousValue, currentValue) => previousValue + currentValue;
  if (array.length % 2 === 0) {

    newArr = array.map((element, index) => index % 2 === 0 ? element * 2 : element);
  } else {
    newArr = array.map((element, index) => index % 2 === 1 ? element * 2 : element);
  }
  newestArr = newArr.map((element) => element > 9 ? element - 9 : element);

  let sum = newestArr.reduce((prev, curr) => prev += curr);
  return sum % 10 === 0
};

const findInvalidCards = (nestedArray) => {
  let invalidArray = [];
  invalidArray = nestedArray.forEach((element) => validateCred(element) === false);
  return invalidArray;
};

findInvalidCards(valid1);

>Solution :

valid1 is supposed to be an array of arrays, so here I just wrap another set of square brackets.

Also, forEach always returns undefined, so I changed it to use map instead.

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

const validateCred = (array) => {
  let newArr = [];
  let newestArr = [];
  let reducedResult = 0;
  const reducer = (previousValue, currentValue) => previousValue + currentValue;
  if (array.length % 2 === 0) {

    newArr = array.map((element, index) => index % 2 === 0 ? element * 2 : element);
  } else {
    newArr = array.map((element, index) => index % 2 === 1 ? element * 2 : element);
  }
  newestArr = newArr.map((element) => element > 9 ? element - 9 : element);

  let sum = newestArr.reduce((prev, curr) => prev += curr);
  return sum % 10 === 0
};

const findInvalidCards = (nestedArray) => {
  let invalidArray = [];
  invalidArray = nestedArray.map((element) => ({cardNumber: element.join(""), isValid: validateCred(element)}));
  return invalidArray;
};

console.log(findInvalidCards(valid1));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading