0

I am doing some Javascript Matrix exercises and came across the problem of my Matrix not updating as expected when it's created using the Javascript Array constructor.

I created a matrix called theatre:

const theatre = new Array(5).fill(new Array(10).fill(0));

which prints as expected:

console.log(theatre)

[ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]

however, when I attempt to change the values of each element in the first two rows to 1, every value in the matrix is changed.

for(let i = 0; i < 2; i++){
  for(let j = 0; j < 10; j++){
        theatre[i][j] = 1;
  }
}

console.log(theatre)

[ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ]

To test further, I updated theatre to be equal to a matrix instead of using the array constructor and ran the for loop again which returned the expected output.

const theatre = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]

for(let i = 0; i < 2; i++){
  for(let j = 0; j < 10; j++){
        theatre[i][j] = 1;
  }
}

console.log(theatre)

[ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]

Why doesn't this logic work as expected on the matrix created with the Array constructor? Am I misunderstanding how the array constructor works with fill?

  • 1
    filling an array with an object using `fill()` fills it with references to a single object, not individual objects. – pilchard May 17 '22 at 20:49
  • also see: [How do you easily create empty matrices javascript?](https://stackoverflow.com/questions/8301400/how-do-you-easily-create-empty-matrices-javascript) and [2-dimensional arrays in ES6](https://stackoverflow.com/questions/49090792/2-dimensional-arrays-in-es6) – pilchard May 17 '22 at 20:52

0 Answers0