0

I've got a list of coordinates and a matrix ( array of arrays filled with 0s ->

[
  [0,0,0,0,0..],
  [0,0,0,0,0...]
   .
   .
]

) for every coordinate i've got i wanna fill a field in the matrix with 1. For some reason when looping through coordinates it fills every Y for certain X instead of just the ones given. Here's the code:

let matrix = new Array(maxY).fill(new Array(maxX).fill(0));
arr.forEach(el => (matrix[el[1]][el[0]] = 1));
console.log(matrix[2][498]);

coordinates input: [ [ 498, 4 ], [ 498, 6 ] ];

given this input, the bottom console.log should show me 0, but it shows 1 for every Y in the array. anybody could help?

  • arr = coordinates – Paweł Czekaj Dec 18 '22 at 03:36
  • 1
    `new Array(maxX).fill(0)` is creating one array in memory and then you're filling the outer array with this one array repeatedly. Therefore, each row is pointing to the same one array in memory – Nick Dec 18 '22 at 03:36

0 Answers0