snippetjavascriptCritical
How can I create a two dimensional array in JavaScript?
Viewed 0 times
arrayhowdimensionalcantwojavascriptcreate
Problem
I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.
-
How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)
-
How would I access its members? (
-
How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)
-
How would I access its members? (
myArray[0][1] or myArray[0,1]?)Solution
Practically? Yes. You can create an array of arrays which functions as an 2D array as every item is an array itself:
But technically this is just an array of arrays and not a “true” 2D array, as I. J. Kennedy pointed out.
It should be noted that you could keep nesting arrays into one another and so create “multidimensional” arrays.
let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);
But technically this is just an array of arrays and not a “true” 2D array, as I. J. Kennedy pointed out.
It should be noted that you could keep nesting arrays into one another and so create “multidimensional” arrays.
Context
Stack Overflow Q#966225, score: 1429
Revisions (0)
No revisions yet.