1

I'm trying to create two dimensional array using fill functions. It's looks like this:

let map = new Array(3)
            .fill(new Array(3)
                .fill(0));

Problem appears when I try to set one value at specific index:

map[1][1] = 1;

I expect to have result:

[[0, 0, 0],[0, 1, 0],[0, 0, 0]]

But I receive this:

[[0, 1, 0],[0, 1, 0],[0, 1, 0]]

It looks like all this subarrays referencing to one array but why?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Anwarus
  • 138
  • 2
  • 11

2 Answers2

5

The problem is that fill(new Array(3)) first makes a new array and then fills the array with that so each element points to the same array reference. When you change one, it's reflected in all of them.

You could use Array.from() for the outer arrays, which takes a function. This will allow you to make a new array for each one:

let map = Array.from(Array(3), () => new Array(3).fill(0)) 

map[1][1] = 1;
console.log(map)

Here it will call the function for each element insuring that that a unique array is made for each one.

Mark
  • 90,562
  • 7
  • 108
  • 148
0

Use this instead:

maps = new Array(3)
            .fill().map(u => new Array(3).fill(0));

maps[1][1] = 1;
Chidi Williams
  • 399
  • 6
  • 16