0

enter code hereI have a batch array that contains three named arrays [valid1, valid2 and valid3]

const valid1 = [4, 5, 3];
const valid2 = [5, 5, 3];
const invalid1 = [3, 7, 1];

const batch = [valid1, valid2, invalid1];

If I try to log the name of the arrays using batch[0], I get the actual content of valid1 instead of the string "valid1".

How could I access the actual name of the arrays within batch? I.e:
I expect console.log(batch[0]); to log "valid1" but it logs [4, 5, 3] instead.

Alvaro_L
  • 1
  • 2
  • 1
    Why do you need the name of the variable? You could use an object instead maybe? – evolutionxbox Oct 21 '22 at 22:44
  • Couldn't you create an array with these string values `["valid1", "valid2", "invalid1"]`, after all, you know the name of the variables while you're writing your code, so you can manually add them as strings as you already know what they are. But I agree, with evolutionxbox, it's strange that you need to access the names of your variables. wWhat do you intend do do with them once you have them? If you're trying to implement dynamic variable names then you need a [different approach](https://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – Nick Parsons Oct 21 '22 at 23:38
  • This is for an exercise in which, using the Luhn algorithm, checks if a credit card is valid. I shorted down the items in the arrays for clarity in my question. I already wrote a function that checks the validity of the cards numbers. Now I need to pass that nested array to check the validity of many credit cards. It works too, but I want to return a string with the name of the array containing the card that says "The valid1 card is not a valid card number" – Alvaro_L Oct 22 '22 at 07:52

1 Answers1

1

It is not possible with an array since arrays store the values at the numeric index of it. If you want to achieve what you want, you should go for objects instead.

For example,

const valid1 = [4, 5, 3];
const valid2 = [5, 5, 3];
const invalid1 = [3, 7, 1];
const batch = { valid1, valid2, invalid1 };
 
for (let key in batch) {
    let Val = batch[key];
    console.log(key + " " + Val);
}