1

I want to create a 10x10 array filled with 0 values, which I though I could do like this:

var myArray = new Array(10).fill(new Array(10).fill(0));

This is working fine, but there's a problem when I try to change one of the values in the array, for example:

myArray[2][3] = 6;

Instead of changing just the one value, the output is this:

0 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
1 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
2 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
3 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
4 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
5 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
6 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
7 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
8 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)
9 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0] (10)

As you can see, all values in the column with index 3 have been changed. Why is this, and how do I create a new, zero-filled array without this happening?

var myArray = new Array(10).fill(new Array(10).fill(0));

console.log("--------Before--------");
console.log(myArray);

myArray[2][3] = 6;

console.log("--------After---------");
console.log(myArray);
Cid
  • 14,968
  • 4
  • 30
  • 45
Run_Script
  • 2,487
  • 2
  • 15
  • 30
  • 2
    `.fill()` does not create a new array for every slot in the array it is called on. There's just one `new Array(10).fill(0)`. Use `Array.from()` and its second parameter (a callback). – Andreas Dec 12 '20 at 10:25
  • 1
    `fill` fills with a constant value, this is for objects the same object reference. – Nina Scholz Dec 12 '20 at 10:26
  • 1
    `new Array(10).fill(null).map(() => new Array(10).fill(0))` will create a new Array for each row (`map` executes a callback for each element, while `fill` does not) – blex Dec 12 '20 at 10:27
  • 2
    @blex `Array.from({length: 10}, () => new Array(10).fill(0))` – Andreas Dec 12 '20 at 10:29
  • @Andreas nice one – blex Dec 12 '20 at 10:31

0 Answers0