0

so i filled this 2D array with 0 and then changing the first value in the first row of this 2D array but it changes the first value in every row, anyone know why this is happening?

let arr = Array<number[]>(5).fill(Array<number>(5).fill(0));

arr[0][0] = 10;
console.log(arr);

output

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

expected output

[
  [ 10, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0 ]
]```
BoredBoi
  • 143
  • 1
  • 2
  • 7
  • 2
    This is not related to Deno this is hows Array.fill works, https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance – Chellappan வ May 22 '21 at 10:11

1 Answers1

2

Array.prototype.fill() sets each element in the array to the specified value. To generate an array filled with possibly different values you can use Array.from():

let arr = Array.from({ length: 5 }, () => Array<number>(5).fill(0));
mfulton26
  • 29,956
  • 6
  • 64
  • 88