1

How to create a [m, n] sized array pre-filled with 0 in ES6

var x = Array.from(Array(5), () => 0)

gives a array of length 5. I need one with 5x3

var x = Array.from(Array(Array.from(Array(3),()=>0)), () => 0)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
DL Narasimhan
  • 731
  • 9
  • 25

2 Answers2

3

Create an array with n zeros:

Array(n).fill(0)

Create an array which contains m times the same array with n zeros:

Array(m).fill(Array(n).fill(0));

Create an array which contains m different arrays with n zeros:

Array(m).fill().map(() => Array(n).fill(0));

Example:

console.log(JSON.stringify( Array(5).fill().map(() => Array(3).fill(0)) ));
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    Also see [Most efficient way to create a zero filled JavaScript array?](http://stackoverflow.com/q/1295584/1529630) and [Array.prototype.fill() with object passes reference and not new instance](http://stackoverflow.com/q/35578478/1529630) – Oriol Jun 13 '16 at 10:28
2

Your syntax is incorrect do it like

var x = Array.from(Array(5), () => Array.from(Array(3), () => 0));

console.log(x);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188