skip to Main Content

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.

2

Answers


  1. You can get the expected output like this:

    ls = ""
    for (var i = 0; i < 3; i++){
       ls += car1[i]+car2[i]+car3[i]+car4[i]+car5[i]
    }
    

    Output: ‘Aa1XxBb2YyCc3Zz’

    Login or Signup to reply.
  2. 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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search