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
Array.from(Array(2), () => new Array(4))
2 and 4 being first and second dimensions respectively.
We are making use of Array.from, which can take an array-like param and an optional mapping for each of the elements.
Array.from(arrayLike[, mapFn[, thisArg]])
var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);
The same trick can be used to Create a JavaScript array containing 1...N
n = 10,000)Array(2).fill(null).map(() => Array(4))
The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map. Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.
var arr = Array(2).fill(null).map(() => Array(4));
arr[0][0] = 'foo';
console.info(arr);
Here's a method that appears correct, but has issues.
Array(2).fill(Array(4)); // BAD! Rows are copied by reference
While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo';
console.info(arr);
console.info(arr[0][0], arr[1][0]);