Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading