Search code examples
javascriptarraysexpressionfillone-liner

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


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));


Solution

  • Try:

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