1

I hit a weird behavior when trying to generate and use symetrically generated 2D Matrices in Node/Chrome. The generating method is shown below.

const test=(f) => {
    // Omitted
    // Could provide full source if needed but it's not small
}
const gen=(boxSize)=>{
    const boardSize = boxSize ** 2;
    return new Array(boardSize).fill(new Array(boardSize).fill(0));
}

console.log(gen(2)); // [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
test(gen(2)); // fails
test(JSON.parse(JSON.stringify(gen(2)))); // passes
test([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]); // passes

Why do I get this inconsistent(?!) behavior between they ways of initializing the arrays?

LeDon
  • 529
  • 7
  • 21

1 Answers1

2

Probably the issue here stems from the fact that all the rows of gen(2) are a reference to the same array. So modifying any row will in fact modify every row; no doubt this is not the behavior you want.

This is because the Array.fill method will use exactly the same thing for each element of the filled array. Note that the thing you're filling with is a reference to another array, thus each element will be a reference to that same array.

To fix this, I would recommend using .map on top of .fill:

return new Array(boardSize).fill().map(() => new Array(boardSize).fill(0))

or perhaps use Array.from:

return Array.from({length: boardSize}, () => new Array(boardSize).fill(0))
CRice
  • 29,968
  • 4
  • 57
  • 70