Reputation: 11628
What is the shortest way to create a 2d array of a certain size?
I figured that following code is pretty short, but can you do it with even less code?
var x = 5;
var y = 7;
var my2dArray = (new Array(y)).fill(0).map(
function(){
return new Array(x);
}
);
Upvotes: 1
Views: 3017
Reputation:
Array.apply(0, Array(x)).map(function() { return Array.apply(0, Array(y)); })
Simpler if you write a little convenience routine
function make_array(x) { return Array.apply(0, Array(x)); }
then
make_array(x).map(function() { return make_array(y);} )
or if you prefer
make_array(x).map(make_array.bind(0, y))
If you're writing ES6:
Array(...Array(x)).map(() => Array(y));
If you'd prefer to use fill
, since you seem to have it available:
Array(x).fill().map(function() { return Array(y); });
or somewhat more concisely in ES6, using an arrow function:
Array(x).fill().map(() => Array(y));
It turns out Array#fill
requires no argument; without it, it replaces absent elements with undefineds.
Upvotes: 11
Reputation: 19294
What about building your own Class ?
function Array2D(xSize, ySize, initialValue) {
initialValue=initialValue || 0;
// create an flat empty array filled with the initial value
var length = xSize*ySize;
var innerArray = new Array(length);
for (var i=0; i<length; i++) innerArray[i] = initialValue;
// accessors
this.getAt = function(x, y) { return innerArray[x+xSize*y]};
this.setAt = function(x, y, val) { innerArray[x+xSize*y]=val};
}
Use with :
var myArray2d = new Array2D(5,7);
myArray2d.setAt(1,1,3);
var value = myArray2d.getAt(1,1); // == 3
var anotherValue = myArray2d.getAt(2,2); // == 0
Upvotes: 3