How can I create a two dimensional array in JavaScript?
arrays, javascript, multidimensional-array
Solution
Practically? Yes. You can create an array of arrays which functions as an 2D array as every item is an array itself:
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.
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? (`myArray[0][1]` or `myArray[0,1]`?)
Related problems
- Array() vs new Array()
- Standard conventions for indicating a function argument is unused in JavaScript
- How to create an array containing 1...N
- What happens if I don't pass a parameter in a Javascript function?
- How to create multidimensional array
- best way to generate empty 2D array
- Autovivification and Javascript