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
Here's a quick way I've found to make a two dimensional array.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(e => Array(y));
}
You can easily turn this function into an ES5 function as well.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(function(e) {
return Array(y);
});
}
Why this works: the new Array(n)
constructor creates an object with a prototype of Array.prototype
and then assigns the object's length
, resulting in an unpopulated array. Due to its lack of actual members we can't run the Array.prototype.map
function on it.
However, when you provide more than one argument to the constructor, such as when you do Array(1, 2, 3, 4)
, the constructor will use the arguments
object to instantiate and populate an Array
object correctly.
For this reason, we can use Array.apply(null, Array(x))
, because the apply
function will spread the arguments into the constructor. For clarification, doing Array.apply(null, Array(3))
is equivalent to doing Array(null, null, null)
.
Now that we've created an actual populated array, all we need to do is call map
and create the second layer (y
).