Home > other >  Why does a single assignment to one 2d array cell fill two cells at once in Javascript?
Why does a single assignment to one 2d array cell fill two cells at once in Javascript?

Time:03-14

I have this code from this leetcode question:


function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number {
    
    const land: boolean[][] = new Array(n).fill(new Array(n).fill(false))
    console.log(land)
    
    dig.forEach(spot => {
        console.log(spot, spot[0], spot[1])
        land[spot[0]][spot[1]] = true
        console.log(land)
    })
    
    console.log(land)
    return 0

};

With this input

n = 2
artifacts = [[0,0,0,0],[0,1,1,1]]
dig = [[0,0],[0,1]]

With this stdout:

[ [ false, false ], [ false, false ] ]

[ 0, 0 ] 0 0

[ [ true, false ], [ true, false ] ] **but expected => [ [ true, false ], [ false, false ] ]

[ 0, 1 ] 0 1

[ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]
[ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]

Why do land[1][0] === true and land[1][1] === true when they are never accessed?

CodePudding user response:

This:

  new Array(n).fill(new Array(n).fill(false))

fills the new outer array with n copies of the same array. The argument to the outer .fill() is computed once, so there's only one array involved for the second dimension.

You can create multiple arrays, one for each row:

const land: boolean[][] = new Array(n);
land.fill("dummy value");
land.forEach((_, i, rows) =>
  rows[i] = new Array(n);
  rows[i].fill(false)
);

In the (edited) code, the outer array is first filled with a dummy value. That's necessary because .forEach() will skip uninitialized entries in an array. Alternatively, a simple for loop could be used, though unless n is enormous it probably doesn't matter.

  • Related