Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one cell in multidimensional array updates entire column

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?

like image 705
maxjvh Avatar asked Dec 06 '15 14:12

maxjvh


People also ask

How do you update a two-dimensional array?

Updating the 2D array We can update the elements of 2D array either by specifying the element to be replaced or by specifying the position where replacment has to be done. For updating the array we require, Elements of an array. Element or position, where it has to be inserted.

How do you modify data in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

How do you update a two-dimensional array in Python?

Updating Values in Python 2D Array We can update a single element in a 2D array by specifying its row and column index and assigning that array position a new value. Assigning a new value overwrites the old value, thus updating it.

How to change values in a 2D array Java?

In Java, elements in a 2D array can be modified in a similar fashion to modifying elements in a 1D array. Setting arr[i][j] equal to a new value will modify the element in row i column j of the array arr .


1 Answers

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.

like image 169
Jason Avatar answered Oct 17 '22 02:10

Jason