views:

81

answers:

2

Is there an easy way to programmatically create a 2d array in javascript?

What I don't want:

var array2D = [ 
  [0,0,0],
  [0,0,0],
  [0,0,0]
]
+2  A: 

Well, you could write a helper function:

function zeros(dimensions) {
    var array = [];

    for (var i = 0; i < dimensions[0]; ++i) {
        array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
    }

    return array;
}

> zeros([5, 3]);
  [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Bonus: handles any number of dimensions.

John Kugelman
Marked down you end up with multiple references to the same array
Tom
@Tom Aye, good call. Rewritten.
John Kugelman
Change `item` to a lambda that is a factory for items.
Ates Goral
@John now marked up
Tom
This could be written much more clearly. Typically when you're writing a recursive function, you should make sure that the base case and inductive case are easily identified. In the code above, both are on the same line -- very confusing. Instead, I would recommend that you check the `dimensions.length === 1` conditional at the top of the function and that you create two `for` loops -- one that creates an array of 0s (the base case) and one that creates an array with `zeros` function calls (the inductive case). Though the resulting code will be more verbose, it's much less confusing.
Xavi
+1  A: 
function zero2D(rows, cols) {
  var array = [], row = [];
  while (cols--) row.push(0);
  while (rows--) array.push(row.slice());
  return array;
}
MooGoo