Trouble with 2D arrays

My function is simple, all I’m trying to do here is generate an empty “field” or two dimensional array with a start position and a specified width and height.

it should look like this:

[
  ['*','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
]

But for some reason my function prints this:

[
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
]

This is really strange since I’m using arr[0][0] = '*' to add the start point to the array after it has already been made.

Here is my code:

function generateField(width, height) {
  let newField = [];
  const row = '░'.repeat(width).split('');

  for (let i = 0; i < height; i++) {
    newField.push(row);
  }

  console.log(newField);
  newField[0][0] = '*'; // problem here
  console.log(newField);

  return newField;
}

const myField = generateField(10, 10);

I’m not really sure why this is happening or how to fix it, so any help would be appreciated.

Try the spread syntax:

newField.push([...row]);

That way you are pushing a copy of the row rather than always the same reference.

1 Like

That works, thanks for the help!

1 Like