Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
like image 553
Vahe J Avatar asked Oct 24 '25 23:10

Vahe J


2 Answers

You can use the callback function of Array.from.

let length = 5;
let res = Array.from({length}, _=>[]);
console.log(res);
like image 193
Unmitigated Avatar answered Oct 26 '25 14:10

Unmitigated


Try:

let radix = 10;
let bucket = [...Array(radix)].map(e=>[])
bucket[0].push(1)
console.log(JSON.stringify(bucket));
like image 27
Spectric Avatar answered Oct 26 '25 12:10

Spectric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!