0

The code I'm working on right now requires me to assign a value to a single cell in a 2-D array. But the assignment doesn't seem to work out as expected.

let b = new Array(3).fill(new Array(3).fill(0));
b[1][1] = 1;
console.log(b.toString());

I just can't really understand why it produces this output.

The below code gives me the output I expect but I would really prefer being able to do it in a manner that resembles the first snippet.

let b = []
for(let i = 0; i < 3; i++){
  b.push([])
  for(let j = 0; j < 3; j++){
    b[i].push(0)
  }  
}
b[1][1] = 1
console.log(b.toString())
Adam Jijo
  • 82
  • 1
  • 7
  • 2
    The first one is an 3-item array, and all three of those entries refer to the exact same nested array, they do not point to different 0,0,0 (later 0,1,0) arrays but the exact same array. If you change that nested array its change is reflected in all three references to it. – luk2302 Aug 02 '20 at 18:23

2 Answers2

2

You can avoid assigning the same array reference by using the built in mapping callback of Array.from()

let b = Array.from({length:3}, (_,i) => Array(3).fill(i));

console.log(b)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

In your first example, it creates one array, then fills every element to that one array. This means that a change in one will be reflected in everything else. If you want to construct a new array for each element, then you could try mapping it:

let b = new Array(3).fill(null).map(_ => new Array(3).fill(0));
b[1][1] = 1;
console.log(b.toString());
Aplet123
  • 33,825
  • 1
  • 29
  • 55