0

Consider the code below. I want to change only the second elements value in the second list in matrix. The problem is, that somehow all elements are changed. How can this be?

let matrix = Array(2).fill(Array(2).fill(0));
// [[0, 0], [0, 0]]
matrix[1][1] = 8
console.log(matrix)
// [[0, 8], [0, 8]]
karl
  • 71
  • 1
  • 8

1 Answers1

0

This is because all elements inside matrix are pointing to or referencing the same list. By wanting to change one instance of the list, you change them all because you thereby change the list being pointed to. To avoid this, create an empty nested array using for-loops instead:

let matr = [];
for (let i = 0; i < 2; i++) {
  matr.push(Array(2).fill(0))
}
matr[1][1] = 8
console.log(matr)
karl
  • 71
  • 1
  • 8