Declare an empty two-dimensional array in Javascript? Declare an empty two-dimensional array in Javascript? arrays arrays

Declare an empty two-dimensional array in Javascript?


You can just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

From the nodejs repl:

> var arry = [];undefined> arry.push([1,2]);1> arry[ [ 1, 2 ] ]> arry.push([2,3]);2> arry[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);3> arry[ [ 1, 2 ],  [ 2, 3 ],  100 ]


If you want to initialize along with the creation, you can use fill and map.

const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));

5 is the number of rows and 4 is the number of columns.


ES6

Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

[...Array(3)].map(x=>Array(5).fill(0))