How do I create a dynamic set of arrays in javascript, to form a hierarchy of arrays? I would like this to work dynamically. How to create a root array, that will always be there, and each new array dynamically created, will be nested in the previous array to form a hierarchy.
Asked
Active
Viewed 814 times
0
-
What have you tried? Also, see if this is relevant http://stackoverflow.com/q/12287490/1615483 – Paul S. Sep 20 '12 at 01:54
1 Answers
0
...do you know what's going in these arrays, or have any idea how big or deep they go?
And are you talking about only indexed arrays, or objects with named properties, as well?
If all you want is arrays:
var rootArr = [],
rootArr[0] = [[],[]],
rootArr[1] = [[ [],[],[ [] ], ]];
So now you've got arrays nested like:
[
[
[],
[]
],
[
[
[],
[],
[
[]
]
]
]
];
As you can probably see, you can happily go on building deeper and deeper arrays.
If you wanted to do this dynamically, you could create them in a for
loop, if you know your values, or a recursive function, if you've got checks...
Keep in mind, though, accessing data inside of these will suck.
To get at the deepest array, you'd have to go:
rootArr[1][0][2][0]; //just to access the array
//then you'd need the index of whatever was inside...

Norguard
- 26,167
- 5
- 41
- 49
-
Ok this looks great. I think I will require objects with named properties. I would like to use the arrays and the hierarchy for them, to be used as nodes in a tree structure. Such as in http://bl.ocks.org/1249394. The contents of each array should represent the nodes, and display some sort of data or string. I dont intend for mine to be nearly as complex as this, I would say 5 values per array max. Also, I am very novice to this, I would like to do this dynamically, can you show a small example of the working of the for loop that I might require. Would really appreciate it :) – user1684586 Sep 20 '12 at 02:13