0

I make a grid like this:

  let columns = Math.floor(width / new Boid().perceptionRadius)
  let rows = Math.floor(height / new Boid().perceptionRadius)
  let grid = {
    grid: Array(rows).fill(Array(columns).fill([])),
    dimensions: {
      width: (width / rows),
      height: (height / columns)
    }
  }

and then I push items to the array like this:

flock.forEach((boid)=>{

    let column = Math.floor(this.position.y / grid.dimensions.height),
        row = Math.floor(this.position.x / grid.dimensions.width);

     grid.grid[row][column].push(this)
})
console.log(grid.grid)

When I look in the output, every tiem in both row and column contains flock.length items, why?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Himmators
  • 14,278
  • 36
  • 132
  • 223
  • This fills an array with a bunch of references to a single array: `Array(columns).fill([])`, later when you push to it you are pushing to all of them. – Paul Sep 08 '19 at 22:14
  • 1
    It's because `Array.prototype.fill` is not as useful as it might appear. It uses a shared reference to a single object; so each cell gets the same array. Just try looping over your rows and columns to initialize each with a new `[ ]`. – Scott Sauyet Sep 08 '19 at 22:14
  • 1
    `grid: Array.from(Array(rows), _ => Array.from(Array(cols), _ => []))` – Paul Sep 08 '19 at 22:20
  • Right now you're only making three arrays (each call to Array creates one and the `[]` creates one more). You have a grid/rows array which is filled with a bunch of references to a single cols array, which is itself filled with a bunch of references to a single cell array. – Paul Sep 08 '19 at 22:25

0 Answers0