How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
If it\'s a simple array var newArra
You can create a 6 x 6 empty array like this:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6)
generates an array with length = 6 and full of undefined
values.undefined
values.undefined
positions.If you need to initialize the grid with a default value:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'
.
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's. Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.