Search code examples
javascriptwebdeployment

how to access different array names and their element with the help of loops?


i have 5 array with similar name and different index associated with its name at the end of array name (car1, car2, car3, car4, car5)

const car1 = ["A", "B", "C"];
const car2 = ["a", "b", "c"];
const car3 = ["1", "2", "3"];
const car4 = ["X", "Y", "Z"];
const car5 = ["x", "y", "z"];

let arrayname;

for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 3; j++) {
    let k = j + 1;
    arrayname = "car" + j;

    console.log(arrayname[i]);
  }

}

Output should be- Aa1XxBb2YyCc3Zz Now I want to make a loop that run 3 times and print the fist element of all the given arrays. But the problem is that the created array name {arrayname = "car" + i;} is working as the new variable. I want it as a existing array name so that i can manipulate my array elements.


Solution

  • You can use eval() function:

    const car1 = ["A", "B", "C"];
    const car2 = ["a", "b", "c"];
    const car3 = ["1", "2", "3"];
    const car4 = ["X", "Y" , "Z"];
    const car5 = ["x", "y" , "z"];
    
    for (let i = 1; i < 6; i++) {
        console.log(eval("car" + i)[2]);
    }
    

    This code will print the 3rd element of each array.

    https://jsfiddle.net/8w7foscx/

    To print "Aa1XxBb2YyCc3Zz":

    let message = "";
    for (let pos = 0; pos < 3; pos++) { // Loop over the element position inside an array
        for (let i = 1; i < 6; i++) { // Loop over arrays
            message += eval("car" + i)[pos];
        }
    }
    console.log(message);
    

    https://jsfiddle.net/8w7foscx/1/