4

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

9
  • What's wrong with your current code? Commented Sep 19, 2021 at 17:07
  • If I were to push an item to bucket[0] like so bucket[0].push(1), the array contents would all have 1 [[10],[10],[10],[10],[10],[10],[10],[10]], which pretty much be undesireable Commented Sep 19, 2021 at 17:11
  • Is this one of those scenarios where If fill can accept a callback, I can return a new empty array from the callback, like so... fill(() => []) fingers crossed...awww, unfortunately that was not the case as hoped Commented Sep 19, 2021 at 17:13
  • 1
    const length = 10, bucket = Array.from({ length }).map(() => []); Commented Sep 19, 2021 at 17:21
  • 1
    @VaheJabagchourian ... It's not about one-liners or being this kind of extra smart . A practical solution very often is just a good enough balanced compromise in between a straightforward as possible but still readable / maintainable implementation. Commented Sep 19, 2021 at 17:34

2 Answers 2

4

You can use the callback function of Array.from.

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

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

1 Comment

Thank you for the specific alternate version using underscore object, this is quite desirable and produces a great readable response, with an object of 5 length that I can infer is assigned to an empty array.
1

Try:

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

1 Comment

This is exactly is the shortest length one liner that meets my desire. Thank you. Now I know which of the two functions (map ,fill) will accept the callback, and corresponding equivalent initialization stements.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.