Hi!
I am a very new to JS, started to learn in June and have time to do so only on evenings. Just trying to learn , but it seems that I don’t even understand where to start from when I read the exercise. Can do nothing without google/GPT even after trying not to ask for the help.
Ok, stop whining and lets ask you for a help. Can you please advice, what s wrong with this function, as I keep receiving the message error:
for (let k = 0; k < nestedInvalid.length; k++) {
TypeError: Cannot read property ‘length’ of undefined at idInvalidCardCompanies
My code is :
function idInvalidCardCompanies(nestedInvalid) {
let companies = ;
for (let k = 0; k < nestedInvalid.length; k++) {
if (nestedInvalid[k][0] === 3) {
companies.push(‘Amex’)
} else if (nestedInvalid[k][0] === 4) {
companies.push(‘Visa’)
} else if (nestedInvalid[k][0] === 5) {
companies.push(‘MasterCard’)
} else if (nestedInvalid[k][0] === 6) {
companies.push(‘Discover’)
} else {
companies.push(‘Company not found’)
};
};
return companies;
};
console.log (idInvalidCardCompanies())
Thank you!
It looks like you forgot the argument when you called idInvalidCardCompanies
You need an array (or cards/arrays) as the argument.
So idInvalidCardCompanies()
should be
idInvalidCardCompanies(batch)
or idInvalidCardCompanies(invalid)
or something similar.
2 Likes
You can go a step further by checking whether the card is invalid and only adding it the the companies
array if the card is invalid. Or you could only add the company to the array only if its not already in the array.
In order to check whether a card is invalid and add it only if that is the case, it may be useful make another if-block and put the other if-blocks inside of it:
function idInvalidCardCompanies(nestedInvalid) {
let companies = [];
for (let k = 0; k < nestedInvalid.length; k++) {
const invalid = !validateCred(nestedInvalid);
if (invalid) {
if (nestedInvalid[k][0] === 3) {
companies.push('Amex')
// more code goes here //
} else {
companies.push('Company not found')
};
} // end of if(invalid)
};
return companies;
};
Or you might add some conditions to the if and else-if conditionals so that a company is added only if its not already in the companies
array:
if (nestedInvalid[k][0] === 3 && !companies.includes('Amex')) {
companies.push('Amex')
and so on.
2 Likes
Hi!
Thank you for spending your time! I understood almost nothing before you explained it , thanks a lot!