0

a general question here, but something is not working right here, I have made a table of iterable points, using 6 arrays containing seven sub arrays each, that each individual array can be accessed with a x and y. Only problem, as depicted is when I update lets say board[0][2] It will update the entire column... even though specified,

I have compiled and sumarized the problem, and made a screenshot attached. Anyone have an idea of what might be going wrong here?

Here is my reproduced sample code

let height = 6;
let width = 6;

let board = []
let row = [];

for(let x = 0; x < width; x++){
  row.push([]);
}

for(let y = 0; y < height; y++){
  board.push(row)
}



board[1][5] = 1;



console.log(board)

//Output:

[
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ]
]

I am trying only to update the 5th array element of the array 1

I was expecting that the individual subArray element to be changed, and I have tried many different ways to implement this.

  • Please create a [mcve] by adding a minimal version of how you are creating and updating arrays. – adiga Feb 01 '23 at 11:09
  • Based on the description, you are pushing the same array reference to each inner array. – adiga Feb 01 '23 at 11:10
  • HI @adiga I created the reproducible example, appreciate your help! – Sean.realitytester Feb 01 '23 at 11:14
  • As mentioned in the previous comment, you are pushing the same `row` reference to board. All the rows are the same. You can fix by nesting the for loops: `for(let y = 0; y < height; y++) { let row = []; for(let x = 0; x < width; x++) { row.push([]); } board.push(row) }` This will create new `row` everytime – adiga Feb 01 '23 at 11:20
  • [Javascript multidimensional array updating specific element](https://stackoverflow.com/questions/9979560) – adiga Feb 01 '23 at 11:21
  • Thank you very much! now ill work towards understand the why and how of this particular problem, thank you – Sean.realitytester Feb 01 '23 at 11:31
  • Thank you all for your help! I understand the issue now, would it be correct to say that each time we redeclare an array with let, we are changing the reference, therefore creating essentially a new array? – Sean.realitytester Feb 01 '23 at 11:42
  • Yes, you create a new array in each `height` iteration and pushing that to `board`. In your original code, same `row` array is pushed 5 times. – adiga Feb 01 '23 at 11:50

1 Answers1

0

maybe use Array.from method without referenced

let height = 6;
let width = 6;

let board = []

for(let y = 0; y < height; y++){
  board.push(Array.from({ length: width }, () => []))
}

board[1][5] = 1;

console.log(board)

board[0][0].push(2);

console.log(board)