Changing one cell in multidimensional array updates entire column
Asked Answered
B

2

7

When creating a new multidimensional array in Chrome's console like this:

var array = Array(10).fill(Array(10).fill(false));

the array looks as expected (inspect with console.table): enter image description here

But when trying to change only one cell in the array: array[5][5] = true; something strange happens: enter image description here

I have been banging my head against the wall for sometime because of this, but can't figure it out. Could this be a bug since Array.fill is an experimental/new feature?

Backwards answered 6/12, 2015 at 14:37 Comment(1)
L
6

It's because you actually only created two arrays. You created an inner array with 10 elements and then an outer array that has 10 elements, each of which reference the same inner array. When you change an element of the inner array and then look at the outer array, you'll see the same change in the inner array repeated 10 times.

Create your outer array with a loop instead so that a new inner array is created for every element of your outer loop.

Leman answered 6/12, 2015 at 14:47 Comment(1)
That's it, thanks! I ended up creating the array like this: Array(10).fill().map(_ => Array(10).fill(false)).Backwards
C
0

Since the answer is in the comments, I'm posting this as an official answer for anyone visiting later:

There are a couple of ways to create a 2D array in Javascript.

  1. Simple, straight-forward answer from @maxjvh
Array(rows).fill().map(_ => Array(columns).fill(value))
  1. Another alternative simple way without using the .map() method
Array.from({ length: rows }, () => Array(columns).fill(value));
  1. Nested Loops
const array = [];
for (let i = 0; i < rows; i++) {
    const row = [];
    for (let j = 0; j < columns; j++) {
        row.push(value);
    }
    array.push(row);
}
  1. Flat Array with Index Calculation (This one is not a 2D array but is an alternative representation of a 2D space)
function create2DArrayAs1D(rows, columns) {
    return new Array(rows * columns).fill(0);
}

function getElement(array, row, column, columns) {
    return array[row * columns + column];
}

function setElement(array, row, column, value, columns) {
    array[row * columns + column] = value;
}
Classmate answered 9/8 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.