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.

prisoner_of_azkaban
  • 700
  • 1
  • 8
  • 26

2 Answers2

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

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
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]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392