How can I make multidimensional array in javascript in the following format:
Array[
{index}:{x-coords}
{y-coords},
{index2}:{x-coords}
{y-coords},
.... ];
The data should look like as follows:
Array[
{
indexabc:{10},{20}
},
{
indexxyz:{30},{40}
}
];
Also, how to access the array elements? I am storing value in them through a function so it will be called recursively.
How can I make multidimensional array in javascript in the following format:
Array[
{index}:{x-coords}
{y-coords},
{index2}:{x-coords}
{y-coords},
.... ];
The data should look like as follows:
Array[
{
indexabc:{10},{20}
},
{
indexxyz:{30},{40}
}
];
Also, how to access the array elements? I am storing value in them through a function so it will be called recursively.
Share Improve this question edited Jun 8, 2016 at 21:11 Arihant asked Jun 8, 2016 at 20:33 ArihantArihant 4,06718 gold badges59 silver badges91 bronze badges 5- please add some example data. – Nina Scholz Commented Jun 8, 2016 at 20:42
- show how should look the expected result for your case – RomanPerekhrest Commented Jun 8, 2016 at 20:42
- @NinaScholz please see the sample data – Arihant Commented Jun 8, 2016 at 21:12
- 1 Where you get this notation? it's not javascript. – vp_arth Commented Jun 9, 2016 at 4:37
- please add the purpose to the question, because it makes a huge difference to the data structure, for example if you need iterable data structure, then an array would be better than an object with keys. but if you know the keys, for example a linked list, the an object structure would be better. so its up to you what you want. – Nina Scholz Commented Jun 9, 2016 at 12:19
3 Answers
Reset to default 5It sounds like you want plain old Object:
var o = {
indexabc: { x: 10, y: 20},
indexxyz: { x: 30, y: 40 }
};
console.log( o.indexabc.x, o.indexabc.y );
If you just want to create a two-dimensional array you can easy do like that:
var a = [];
a[0] = [1,2];
a[1] = [2,3];
console.log(a[0]) // [1,2]
var arr = [[x-coords, y-coords], [x-coords, y-coords]...]
is a multidimensional array, however if you want key - value pairs, you might want to use an object
var obj = {
index: [x-coords, y-coords],
index2: [x-coords, y-coords],
...
}
to fit your data either use William B's answer or something like that
var obj = {
indexabc: [10, 20],
indexxyz: [30, 40]
}
so you can access data like so
obj.indexabc[0]