Nested Array : change the value of an element

Hi,

I am doing the challenge of ‘find your hat’, I am writing a function to create a new map, i have 2 for loops that creates the array of the map.
I want to modify only the first element of the array but I can’t find how to do it, here the code:

const fieldCharacter = ‘░’;
const pathCharacter = ‘*’;

function randomField(x,y){
let arr=;
let lines=;
for(let i=0;i<y;i++){
lines[i]=fieldCharacter;
};
for(let p=0; p<x;p++){
arr.push(lines);
};
arr[0][0] = pathCharacter;

console.log(arr);
}

if I do like this instead of changing the first element of the first array it modifies all the first elements of all the arrays and the result is this:

[ [ ‘’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ '
’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ ‘’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ '
’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ ‘*’, ‘░’, ‘░’, ‘░’, ‘░’ ] ]

instead of this ( that is what I expect the function to do):
[ [ ‘*’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ ‘░’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ ‘░’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ ‘░’, ‘░’, ‘░’, ‘░’, ‘░’ ],
[ ‘░’, ‘░’, ‘░’, ‘░’, ‘░’ ] ]

Thanks for your help!

Welcome to the forums!

Your lines array is being pushed multiple times into arr, but lines still references the original array you created. Anywhere that array is referenced will be changed as well.

Example:

const testA = [1,2,3];
const testB = [];

testB.push(testA); // Push testA into testB
console.log(testB); // log testB: [ [ 1, 2, 3 ] ]
testB[0][0] = 7; // Change a value in testB
console.log(testA); // Log testA, the value changes: [ 7, 2, 3 ]

You’ll have to come up with a way of generating the field that doesn’t push the same array multiple times. Looks like you’re close though - good luck!

hint:

Probaby not a great amount of help to the OP based on the time that’s passed but for anyone else who gets stuck. I am working through this now. I had the same problem and found a workaround after reading the reply from ryansup. There is no equivalent of the ‘line’ variable now as the additional rows are populated through a function call.

generateField(x, y, percentage) {
    const getMapRow = () => {
      let mapRow = [];
      for (let i = 0; i < x; i++) {
        mapRow.push(fieldCharacter);
      }
      return mapRow; // Returns the array of fields based on x value
    };
    const getMap = () => {
      let map = []
      for (let j = 0; j < y; j++) {
        map.push(getMapRow());
      }
      return map; // Generates y number of rows of the getMapRow function
    }
    const map = getMap();
    map[0][0] = pathCharacter;
    console.log(map);
  }

Not sure whether this is the best way to get around this but if it works, it works.