How do I fill a new array with n distinct empty arrays, in a concise one-line initialization statement?

Viewed 513

Here is where I am stuck. I want to take this statement and revise it in a manner that the empty array I fill (which I surmise might not work with dynamic values), will initialize bucket to the n distinct empty arrays.

How do I do this? Is there a way to make this fill method behave in the intended manner?

let radix = 10;
let badBucket = [...Array(radix).fill([])];
let goodBucket = JSON.parse(JSON.stringify([...Array(radix).fill([])]));
badBucket[3].push(33);
goodBucket[3].push(33);
console.log(JSON.stringify(badBucket));
console.log(JSON.stringify(goodBucket));

2 Answers

You can use the callback function of Array.from.

let length = 5;
let res = Array.from({length}, _=>[]);
console.log(res);

Try:

let radix = 10;
let bucket = [...Array(radix)].map(e=>[])
bucket[0].push(1)
console.log(JSON.stringify(bucket));

Related