how do you create a 2-d array initialized with zeroes in javascript?

If we run:

let a = new Array(2).fill(new Array(3).fill([0, 0]));
for (let i=0; i<2; i++) {
  for (let j=0; j<3; j++) {
    a[i][j] = [i, j];
    console.log(a[i][j]);
  }
}
console.log(a);

We find that there’s nothing wrong with the loop’s logic itself. It is going in the correct order for i and j. So what’s the problem? It turns out that JavaScript’s Array.fill() method creates copies by references, not values! In other words, each element is basically a reference pointing to the same array, not individual separate arrays. To fix this for your code, use Array.from():

let a = Array.from({length: 2}, e => Array.from({length:3}, e => [0, 0]));
for (let i=0; i<2; i++) {
  for (let j=0; j<3; j++) {
    a[i][j] = [i, j];
    console.log(a[i][j]);
  }
}
console.log(a);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top