Loop through dynamically named arrays

Samij

I have a number of arrays with dynamic names (numbered), and I need to get first value out of each of them.

The code looks like this

    var array1 = ["1","2","3"];
    var array2 = ["1","2","3"];
    var array3 = ["1","2","3"];

    for (var cols=1; cols <=5; cols++) {
        var imgs = array.cols[0];
    }

I get "(index):131 Uncaught ReferenceError: arrays is not defined" in console

Shidersz

If your arrays are in the global scope, maybe you can access they using window object:

var array1 = ["1","2","3"];
var array2 = ["1","2","3"];
var array3 = ["1","2","3"];

for (let i = 1; i <= 3; i++)
{
    console.log(window["array" + i][0]);
}

Another, more generic, alternative is to save your arrays inside another structure, like a Map or an Array. I will show how yo can do it with a Map:

let array1 = ["1","2","3"];
let array2 = ["1","2","3"];
let array3 = ["1","2","3"];
let myMap = new Map([["1", array1], ["2", array2], ["3", array3]]);

myMap.forEach(([first, ...rest]) => console.log(first));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Loop through multiple arrays and list the result dynamically

From Dev

Creating Arrays Dynamically with a for loop

From Dev

Python loop with dynamically named outputs

From Dev

Loop through arrays manually

From Dev

Loop through a collection of Arrays and return named key value pairs (Laravel/Eloquent)

From Dev

Loop through named range list

From Dev

Combine varied number of dynamically named arrays

From Dev

Loop through SQL columns Dynamically

From Dev

dynamically loop through Pug variables

From Dev

Perl loop through hash of arrays

From Dev

How to loop through arrays in reactjs

From Dev

Lodash loop through an array of arrays

From Dev

How to loop through an array of arrays?

From Dev

Loop through nested arrays PHP

From Dev

Arithmetic for loop through arrays of pointers

From Dev

Loop randomly through multiple arrays

From Dev

loop through array of arrays of arrays php

From Dev

For Loop through Named Range cells names

From Dev

Use named range to loop through sheets

From Dev

Excel VBA Loop Through Named Ranges

From Dev

Loop Through All Worksheets Except Those Named

From Dev

How to loop through named range label automatically

From Dev

How to loop through a list of files that are sequentially named?

From Dev

How to loop in nested loop through multiple arrays?

From Dev

Loop through dynamically generated array in bash

From Dev

Loop through local folder & dynamically create elements

From Dev

How to loop through dynamically added elements in DOM

From Dev

How to loop through dynamically generated answerkeys?

From Dev

Ansible: assign and loop through list dynamically