Your problem is this function.
function createArr(rows, columns) {
var rowArr = [];
for(var i = 0; i < columns; i++) {
rowArr.push(0);
}
for(var y = 0; y < rows; y++) {
gridArr.push(rowArr);
}
}
Notice this line
gridArr.push(rowArr)
What does it do?
It does not a create a new row array. All it does is copy reference of the same row array.
Check this:-
createArr(10,20)
console.log(gridArr[0]===gridArr[1]) // gives => true, should give false
Change your code like this-
function createArr(rows, columns) {
for(var y = 0; y < rows; y++) {
gridArr.push(new Array(columns));
}
}
And you should be fine.
If you really need to fill your array with zeros.
function createArr(rows, columns) {
for(var y = 0; y < rows; y++) {
var newRowArray = Array.apply(null, new Array(columns)).map(()=>0);
gridArr.push(newRowArray);
}
}
Feel free to ask for further explanation.
Side Note:- If you don’t want to deal with 2d arrays and make your life simpler, you could just use 1d arrays.
Create a new array and randomly fill them with 1s or 0s-
function createArrayWithRandomValues(size) {
var arr = [];
for (var i=0; i<size; i++) {
arr[i] = Math.round(Math.random());
}
return arr;
}
When you want to convert 2d indices to 1d ones, like - [3][7] to corresponding 1d index (and vice versa) values it can be done on demand.