Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a 2d array of zeroes in javascript?

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]
]
like image 996
Travis Avatar asked Sep 11 '10 05:09

Travis


4 Answers

Solution 2017:

Late to the Party, but this Post is still high up in the Google search results.

To create an empty 2D-Array with given size (adaptable for more dimensions):

let array = Array(rows).fill().map(() => Array(columns));

Prefilled 2D-Array:

let array = Array(rows).fill().map(() => Array(columns).fill(0));

E.g.:

Array(2).fill().map(() => Array(3).fill(42));
// Result:
// [[42, 42, 42],
//  [42, 42, 42]]

Warning:

Array(rows).fill(Array(columns)) will result in all rows being the reference to the same array!!


Update 24th September 2018 (thanks to @Tyler):

Another possible approach is to use Array.fill() to apply the map function.

E.g.:

Array.from(Array(2), _ => Array(3).fill(43));
// Result:
// [[43, 43, 43],
//  [43, 43, 43]]

Benchmark:

https://jsperf.com/multi-dimensional-array-map-vs-fill/5

like image 72
FatalMerlin Avatar answered Sep 24 '22 02:09

FatalMerlin


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.

like image 44
John Kugelman Avatar answered Sep 22 '22 02:09

John Kugelman


function zero2D(rows, cols) {
  var array = [], row = [];
  while (cols--) row.push(0);
  while (rows--) array.push(row.slice());
  return array;
}
like image 45
MooGoo Avatar answered Sep 26 '22 02:09

MooGoo


You can use the following function to create a 2D array of zeros:

const zeros = (m, n) => [...Array(m)].map(e => Array(n).fill(0));

console.log(zeros(3, 4));

// [ [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ] ]
like image 28
Grant Miller Avatar answered Sep 26 '22 02:09

Grant Miller