3

I'm using the following code to create a 2D array of booleans (initially filled with false), and then flipping the value individually.

constructor(props) {
  super(props);

  this.state = {
    fullGrid: Array(3).fill(Array(5).fill(false))
  };
  this.toggleFullGrid = this.toggleFullGrid.bind(this);
}

//Toggles boolean value found at id
toggleFullGrid(cols, rows) {
  alert("This is index.js, we got everything: " + cols + " " + rows);
  let alteredGrid = this.state.fullGrid;
  console.log(alteredGrid);
  console.log(cols + " " + rows);
  console.log(alteredGrid[cols][rows]);

  //change alteredGrid at cols,rows
  alteredGrid[cols][rows] = !alteredGrid[cols][rows];
  console.log(alteredGrid);

  this.setState({fullGrid: alteredGrid});
}

However, rather than flipping individual values, this causes an entire column to be flipped (in a very confusing way). Here's the console output:

(3) [Array(5), Array(5), Array(5)]
  0 : (5) [true, false, false, false, false]
  1 : (5) [true, false, false, false, false]
  2 : (5) [true, false, false, false, false]
  length : 3
  __proto__ :  Array(0)

index.js:21 0 0

index.js:22 false

index.js:26 
(3) [Array(5), Array(5), Array(5)]
  0 : (5) [true, false, false, false, false]
  1 : (5) [true, false, false, false, false]
  2 : (5) [true, false, false, false, false]
  length : 3
  __proto__ : Array(0)

The first array is a copy of before the flip, so I'm unsure why it's not all false. The second and third output prove that the program knows what it's flipping and where. The fourth output (second array) is identical to the first one.

Furthermore, it's not truly updating either. The state change should force other elements to update (and change color based on whether they correspond to true or false in the array), but that is not happening.

Question: Why is it flipping the entire column? Why is the first outputted array the same as the second outputted array? How would I get it to flip single values? How would I get it to update correctly?

Also, someone told me weird things happen with arrays in javascript when trying to flip values, so I tested a version where I saved the array value to a separate var, flipped that, and then saved it back. The result was identical.

2 Answers 2

4

Seems like the way you have used Array.fill() is causing the issue.

The reason for this is, that there has only been one row, which had internally been referenced three times. So when you changed any cell in any row, that particular cell in other rows also change.

You can use the Array fill like this :

this.state = {
  fullGrid : Array(3).fill(0).map(row => new Array(5).fill(false))
}

The above solution will first create an array with 0s and then map each row with a new array in which you can fill false.

Also you can test that:

var a =  new Array(3).fill(new Array(5).fill(false));
(3) [Array(5), Array(5), Array(5)]
  0 : (5) [false, false, false, false, false]
  1 : (5) [false, false, false, false, false]
  2 : (5) [false, false, false, false, false]
  length : 3
  __proto__ :  Array(0)

if you do

a[0][0] = true

now a will become :

(3) [Array(5), Array(5), Array(5)]
  0 : (5) [true, false, false, false, false]
  1 : (5) [true, false, false, false, false]
  2 : (5) [true, false, false, false, false]
  length : 3
  __proto__ :  Array(0)

Since the value is changed by reference, each row's first cell has become true.

Your console.log output is same because console.log happens in an asynchronous manner.

Checkout this link for more details about it

2

Welcome to the magical (sic!) world of Javascript Arrays, References and Mutable objects!


To answer: Why is it flipping the entire column?

Arrays do not work like simple values (booleans, string, numbers) where data are copied. When you assign a variable an array, you are only assigning its reference not the actual object (all non-primitive values in javascript are objects).

So to follow what you wrote:

Array(3).fill(Array(5).fill(false)) is two statements:

  1. Array(5).fill(false)
  2. Array(3).fill(...)

In the first one, you create one Array(5) filled with false, and in the second, you fill a new Array(3) with the same Array(5) 3 times.

So when you alter the array[0][0] you are actually modifying the same object behind it, and you find yourself altering three different references, but still the same and only Array(5) created before.


To answer: Why is the first outputted array the same as the second outputted array?

Because a console.log does not freeze the values displayed, and if it usually works for simple values, it is not immediate. The time needed to "print" the value in the console, the original array has already been altered. And because you print a reference, this reference will reflect changes applied to its value.

I'm sorry if it's not really comprehensible, as it's difficult for me to explain properly how it works as English it's not my mother-tongue.


To answer: How would I get it to flip single values? How would I get it to update correctly?

You need to work with "Immutable" values.

First, create a truly immutable state:

const array5 = Array(5).fill(false);
this.state = {
    fullGrid: Array(3).fill(null).map(() => array5.slice())
};

Then, when working with your state, also copy the new array to work with:

let alteredGrid = this.state.fullGrid.slice();

Now, you are safe to set your new clean state which will properly replace the old state.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.