How do you easily create empty matrices javascript?

The Solution to How do you easily create empty matrices javascript? is


Consider using fill:


The idea here is that fill() will fill out the items with undefined, which is enough to get map to work on them.

You could also fill directly:


Alternatives to Array(9).fill() include


We can rewrite the solution a bit more semantically as:

function array9() { return Array(9).fill(); }


function array(n) { return Array(n).fill(); }
array(9).map(() => array(9))

Array.from provides us with an optional second mapping argument, so we have the alternative of writing

Array.from(Array(9), () => Array.from(Array(9));

or, if you prefer

function array9(map) { return Array.from(Array(9), map); }

For verbose description and examples, see Mozilla's Docs on Array.prototype.fill() here.
and for Array.from(), here.

Note that neither Array.prototype.fill() nor Array.from() has support in Internet Explorer. A polyfill for IE is available at the above MDN links.


partition(Array(81), 9)

if you have a partition utility handy. Here's a quick recursive one:

function partition(a, n) {
  return a.length ? [a.splice(0, n)].concat(partition(a, n)) : [];


We can loop a bit more efficiently with

var a = [], b;
while (a.push(b = []) < 9) while (b.push(null) < 9);

Taking advantage of the fact that push returns the new array length.

~ Answered on 2015-10-12 11:19:19

Most Viewed Questions: