0

So I have been trying to create an empty 2d array and trying to push values into it. The following code is as follows.

// Create an array like [[],[]]
let series = new Array(2).fill([]);
//try to push value into the array in position 0 like [[5],[]]
series[0].push(5); // output here is [[5],[5]]

How can I push element to the array at index 0?

There is something I'm missing. Any help is appreciated!!

2 Answers2

1

When you use fill([]) it creates one array and fills everything with a reference to that one array. You can use something like map() or Array.from() which will create a new array object with each iteration:

let series =  Array.from({length: 2}, () => []);

series[0].push(5); 
console.log(series)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Use [...Array(2)].map(a=>[]); instead.

When you use fill you assign the same object reference to everything

let series = [...Array(2)].map(a=>[]);
series[0].push(5);

console.log(series)