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: