Initializing new object with random values for each elem in 2D javascript array?

Viewed 92

I am trying to do this basic iteration and object initialization but it seems like every row is being created with the object containing same ids. Am I getting crazy?

function makeGrid (cols, rows) {
  const grid = new Array(cols).fill(new Array(rows))
  for (let i = 0; i < cols; i++) {
    for (let j = 0; j < rows; j++) {
      grid[i][j] = {id: random()}
    }
  }
  return grid
}

This is the result: enter image description here

2 Answers

Thanks to @Scott Hunter and @ASDFGerte (in the comments): The problem was new Array(cols).fill(new Array(rows)). This is filling the newly initiated array with references to another new array new Array(rows). What I wanted to do is creating new arrays for every element in the cols array. This solves the issue:

[...new Array(cols)].map(() => new Array(rows))

this works but is not recommended. Id's must be unique and using random doesn't guarantee that they will be.

function makeGrid (cols, rows) {
  var grid = new Array(cols)
  for (let i = 0; i < cols; i++) {
     grid[i] = new Array(rows)      
    for (let j = 0; j < rows; j++) {
      grid[i][j]=  {id: Math.floor(Math.random()*1000 )  }  ;
    }
  }
  console.log(grid);
}

makeGrid(3,4)

Related