Reputation: 145
Per the title, I'm trying to create an array that is filled with any number of empty arrays in JavaScript.
As an example, let's say I wanted to create an array filled with 9 empty arrays. I could do something like this, which works, but looks quite bad:
let myArray = [[], [], [], [], [], [], [], [], []];
I tried using the fill method, but if I push to any of the empty arrays, the other arrays get filled as well:
let myArray = Array(9).fill([]);
myArray[0].push(1);
// Output = [[1], [1], [1], [1], [1], [1], [1], [1], [1]];
Is there a better way to do this? Perhaps a nice one-liner?
Upvotes: 3
Views: 970
Reputation: 31987
Fill it with Array.fill
, then map
over each item:
let myArray = Array(9).fill().map(e => [])
myArray[0].push(1);
console.log(myArray)
Upvotes: 5