-1

I need to dynamically create arrays in runtime based on count. For example if I have an source array sourcearr = ['arr1','arr2','arr3','arr4'], the count of the elements of sourcearr is 4 i.e. var count = sourcearr.length, I need something like:

for(i=0;i<count;i++)
{
    //define 4 dynamic arrays here
    //basically create arr1 = [],arr2 =[], arr3=[],arr4=[]; dynamically.
}

Is there any way to create and then access these arrays dynamically?

vdrog
  • 61
  • 1
  • 7
  • you can with `eval`, but generally you can just use multi-dimensional array instead – Fabricator Sep 25 '17 at 22:20
  • 1
    `eval` is never a good choise! `eval is evil` – Joshua K Sep 25 '17 at 22:21
  • 1
    Please specify why do you think you need this? Normaly such a wish is pointing out a design problem. – Joshua K Sep 25 '17 at 22:22
  • Inside your sourcearr the values of the indices could be arrays instead of a string. Then when you iterate over the arrays you could dynamically set their values. If you need the sourcearr to be strings, I would just create a new `dynamicarr` and set the values there. – kyle Sep 25 '17 at 22:22
  • you would be better with a multiple dimension array or an object that holds arrays – epascarello Sep 25 '17 at 22:24
  • You can set them on the window object, but the better thing to do would be store them in a locally defined object. `window[sourcearr[i]] = []`, or `var myArrs = {}; for(...) { myArrs[sourcearr[i]] = [] }` – mhodges Sep 25 '17 at 22:24
  • @JoshuaK I am trying to parse a .csv file. The .csv file contains column headers and columnar data. My goal is to be able to read the first row of the csv, count the number of headers, create an array for each header and store the values of the columns in the arrays. I need it to be dynamic because the number of columns in the source csv is dynamic. – vdrog Sep 25 '17 at 22:30
  • In my logic, I would create an object and then add those columns as properties of my object. – Lucas_Santos Sep 25 '17 at 22:33
  • 2
    follow the suggestion of using an 2d array. Just define a variable as an array and inside this array you define an array for each column. – Joshua K Sep 25 '17 at 22:38
  • Can you please provide an example @Lucas_Santos ? – vdrog Sep 25 '17 at 22:38

1 Answers1

0

I don't know what you are trying to do, but that should work like you want it.

var count = sourcearr.length;

var container = [];

for (i = 0; i < count; i++) {
  var newArray = new Array();
  newArray = ['x' , i]; // just example values
  container.push(newArray);
}

console.log(container[0][1]); // access the second value of the first array

So in general it's just a multidimensional array

Nico
  • 320
  • 1
  • 4
  • 12