2

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 2

3

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));}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explation, though in you code why should I declared arr = Array(3) if I push 3 times?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.