0

Sorry if my question isn't worded quite right, the following should explain:

I have two 2D arrays:

const letterA = [ [...],[...],...];
const letterB = [ [...],[...],...];
const letterArray["A","B"];

I would like to reference them using a for loop similar to:

let i = 0;
for(i = 0; i < letterArray.length; i++){
  letter[ letterArray[i] ][foo][foo1]; //Here is my trouble
}

Could someone please explain the syntax needed to do this?

Edit: I tried doing the following:

eval('letter'+letterArray[i])[j][k]

however this only got me the error:

ReferenceError: letterA is not defined
  • You have not defined letter, foo and foo1. And not used letterA and letterB. It will be helpful if you can make your question a bit more clearer. – Tech Solver Mar 07 '20 at 03:58
  • I'm trying to reference the array letterA in my first iteration, and the array letterB in the second. foo and foo1 should be ignored, I'm only interested in switching arrays dependent on what the variable i is currently. Something like letter.concat(letterArray[i])[foo][foo1]; ? – Kyle Batchelor Mar 07 '20 at 04:08
  • You can try creating another array, parentArray. And push letterA and letterB and any other arrays into it. And later you can loop through that parentArray. That is the best dynamic option. – Tech Solver Mar 07 '20 at 04:15
  • https://stackoverflow.com/questions/6645067/javascript-dynamically-creating-variables-for-loops – Tech Solver Mar 07 '20 at 04:17
  • I think the above solution might help you. – Tech Solver Mar 07 '20 at 04:17
  • These are very close to what I am trying to accomplish, seems similar to dynamically named variables. – Kyle Batchelor Mar 07 '20 at 04:55

1 Answers1

0

I solved the issue by putting letterA and letterB inside of a dictionary and referencing it like this:

letters = {
letterA : [ [...],[...],...],
letterB : [ [...],[...],...]
};

for(var letter in letters){
    letters[letter][j][k];
}

Thank you for the help, -Kyle