1

So I have a matrix A, of dimension n*n, initialized with Array.fill() like so. var A = new Array(n).fill(new Array(n).fill(0))

That's cool and all however if I try to modify one of its values, the whole column modifies instead. A[2][3] = 1 modifies the whole column 3.

Example snippet :

var n = 4;
var A = new Array(n).fill(new Array(n).fill(0));
console.log(JSON.stringify(A));

A[2][2] = 4;
console.log(JSON.stringify(A)); // ... 

Why is that? o.O

Ionut Eugen
  • 481
  • 2
  • 6
  • 27
  • Does this answer your question? [How to create a 2d array of zeroes in javascript?](https://stackoverflow.com/questions/3689903/how-to-create-a-2d-array-of-zeroes-in-javascript) – pilchard Mar 14 '21 at 11:01

2 Answers2

1

That is bacause your first Array.fill call is using the same array reference to fill those 4 spots and only one inner array is created. So instead of first fill call you could use Array.from which is going to create new array for every spot.

var n = 4;
var A = Array.from(new Array(n), () => new Array(n).fill(0))
console.log(JSON.stringify(A));

A[2][2] = 4;
console.log(JSON.stringify(A)); // ..
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Per MDN, Array.fill

If the first parameter is an object, each slot in the array will reference that object.

That is if the value you're filling the array with is an object, all elements will reference the same object and not a copy of the array

const n = 4;
const array = new Array(n);
for (let i = 0; i < n; i++) array[i] = new Array(n).fill(0);

console.log(JSON.stringify(array));

array[2][2] = 4;

console.log(JSON.stringify(array));
a.mola
  • 3,883
  • 7
  • 23