2

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

3
  • How do you know each row is a different object (as opposed to each being a reference to the same object)? Commented Mar 14, 2020 at 22:57
  • 2
    .fill(new Array(rows)) this is your problem. Use e.g. .fill().map(_ => new Array(rows)); Commented Mar 14, 2020 at 22:58
  • Thank you! I couldn't see the reference problem there. That made it. Commented Mar 14, 2020 at 23:15

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

that was a mock code, IDs don't matter here, that was not the question nor the problem. but thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.