Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : change cell value in 2D array

so, I have a 2d array, which i decalre like this:

var grille = new Array(60).fill(new Array(30).fill(false));

I want to be able to change the value of one cell in the array, but when i do

grille[x][y] = "new value";

I have all the x array which contains "new value" at the index y, instead of array[x][y].

so i have

grille[1][y] = "new value"
grille[2][y] = "new value"
grille[3][y] = "new value"

instead of

grille[x][y] = "new value"
grille[1][y] = false

for example. It may be a noob error, but i'm very new to javascript and don't know how to do this.

Thanks for your help.

like image 589
Joël Avatar asked Mar 08 '17 14:03

Joël


2 Answers

In your case 'new Array(30).fill(false)' will be created only once. It wont be created for each element in 'new Array(60)'. So all 60 cells holds the same array reference. So, if you change one - it will update all its reference.

var grille = (new Array(60)).fill().map(function(){ return new Array(30).fill(false);});

Here, for each element in 'new Array(60)' 'new Array(30)' will be created and each cell hold a different reference now. Hope this helps.

like image 130
ajai Jothi Avatar answered Nov 20 '22 15:11

ajai Jothi


So what I was doing with this is that var grille = new Array(60).fill(new Array(30).fill(false)); filled grille with the same new array(30) and it wasn't creating a new array for each index of grille like I thought. So What I did instead is this

grille= new Array(60);
for (var i = 0; i < grille.length; i++) {
    grille[i] = new Array(30).fill(false);
}
like image 1
Joël Avatar answered Nov 20 '22 14:11

Joël