0

I created a new 2d matrix filled with zeros:

const matrix = new Array(10).fill(new Array(10).fill(0));
matrix[0][0] = -1

When I try to change the value at matrix[row][col], it changes every value in the first row of the matrix.

[
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0],
 [-1,0,0,0,0,0,0,0,0,0]
]
Opp
  • 520
  • 1
  • 8
  • 21

1 Answers1

0

You created one array and used it 10 times in the parent array.

You have to create a new one each time.

const matrix = new Array(10).fill(0).map(() => new Array(10).fill(0));
matrix[0][0] = -1

console.log(matrix.map(e => e.join(',')).join('\n'))
Konrad
  • 21,590
  • 4
  • 28
  • 64