2

I am creating a map of array using this:

var m = new Map(Array(40).fill(new Array()).entries()); 

Now, I want to push values in those array. But when I do this:

m.get(1).push(10) 

The value 10 gets pushed into all the arrays instead of the one at 1st position.

0

2 Answers 2

1

You could take another pattern to build independent arrays.

var m = new Map(Array.from({ length: 40 }, _=> []).entries()); m.get(1).push(10); console.log([...m]);

Sign up to request clarification or add additional context in comments.

Comments

1

fill gets single array an uses it to fill all rows of the given array, it doesn't create a new array for each row. This means that your single array reference is shared between all rows. Because array is a reference type, you use the single reference to manipulate it, so the actual object is changed. You can check this by comparing the references of each row.

const arr = new Array(2).fill(new Array()); console.log(arr[0] === arr[1]);

For creating separate arrays, you can see @Nina's answer above

8 Comments

You're only confirming what the OP figured out...
Need each answer to have full answer to the question, every aspect???
Can't it refer some part to another one?
This doesn't answer the question. You're not explaining how to properly set a value in only one position of the "map".
See also the above comment
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.