Nested arrays manipulation weird behaviour, js

Viewed 65

I have a table of cells that need to be manipulated in a few specific spots accords to data I get


let arr = Array(3).fill(Array(3).fill(0));

[{x: 0, y: 0, value: 1}, {x: 1, y: 0, value: 2},{x: 2, y: 0, value: 3}].map(pos => 
   arr[pos.x][pos.y] = pos.value
)
   console.log(arr)

I expected the code to give [[1,0,0],[2,0,0],[3,0,0]] but instead it give [[3,0,0],[3,0,0],[3,0,0]], in other words it draws all as last y (value 3) and ignore the [pos.x] for some reason, don't sure why.

I'd liked to get some help with a possible workaround as explanation why this code not working as I expecting

thanks in advance!

2 Answers

the problem is when you do the outer fill , that fill function is executed only once, so basically you are having reference to same array in the nested arrays, so when you map you keep updating that same reference and hence all are same in the end

you might wanna do

let arr = [];

for(let i = 0; i < 3; i++) { arr.push(Array(3).fill(0));}

Try this instead:

var arr = Array.from({length:3},()=>Array(3).fill(0));
[{x: 0, y: 0, value: 1}, {x: 1, y: 0, value: 2},{x: 2, y: 0, value: 3}].map(pos => 
  arr[pos.x][pos.y] = pos.value
)
console.log(arr);

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Related