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 dec
ES6+, ES2015+ can do this in even simpler way
Creating 3 x 2 Array filled with true
[...Array(3)].map(item => Array(2).fill(true))
I'm not sure if anyone has answered this but I found this worked for me pretty well -
var array = [[,],[,]]
eg:
var a = [[1,2],[3,4]]
For a 2 dimensional array, for instance.
For one liner lovers Array.from()
// creates 8x8 array filed with "0"
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))
Another one (from comment by dmitry_romanov) use Array().fill()
// creates 8x8 array filed with "0"
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))
Using ES6+ spread operator ("inspired" by InspiredJW answer :) )
// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))
Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.
The following function can be used to construct a 2-d array of fixed dimensions:
function Create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
The number of columns is not really important, because it is not required to specify the size of an array before using it.
Then you can just call:
var arr = Create2DArray(100);
arr[50][2] = 5;
arr[70][5] = 7454;
// ...
To create a 2D array in javaScript we can create an Array first and then add Arrays as it's elements. This method will return a 2D array with the given number of rows and columns.
function Create2DArray(rows,columns) {
var x = new Array(rows);
for (var i = 0; i < rows; i++) {
x[i] = new Array(columns);
}
return x;
}
to create an Array use this method as below.
var array = Create2DArray(10,20);
The sanest answer seems to be
var nrows = ~~(Math.random() * 10);
var ncols = ~~(Math.random() * 10);
console.log(`rows:${nrows}`);
console.log(`cols:${ncols}`);
var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0));
console.log(matrix);
Note we can't directly fill with the rows since fill uses shallow copy constructor, therefore all rows would share the same memory...here is example which demonstrates how each row would be shared (taken from other answers):
// DON'T do this: each row in arr, is shared
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo'; // also modifies arr[1][0]
console.info(arr);