3

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?

1 Answer 1

6

Fill it with Array.fill, then map over each item:

let myArray = Array(9).fill().map(e => [])
myArray[0].push(1);

console.log(myArray)

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

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.