2

My function is following

export const addressGenerator = (total: number, type: AllowedAddressTypes) => {
    console.log("creating total of", total)
    const f = getExecutable(type)
    const result = new Array(total).map(_ => f())
    console.log(result)
    return result
}

I call it as

addressGenerator(20, 'city')

What I see in logs is

creating total of 20
[ 'South Malloryburgh' ]
result 20 [ 'South Malloryburgh' ]

But always an array of 1 is created. When I hardcode the line

new Array(20).map(_ => f())

I do see an array of 20 being created. Given that total is of number type, I am wondering what am I missing?

Can anyone give me a fresh perspective? Thank you

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • 4
    Try `[...Array(20)]` or `Array(20).fill()` before `map`. – ggorlen Apr 15 '21 at 17:44
  • Yes, that's expected. It's why a lot of the answers in [javascript create empty array of a given size](https://stackoverflow.com/a/41246860/691711) have things like `Array(4).fill(null)`. – zero298 Apr 15 '21 at 17:45
  • 1
    Does this answer your question? [Why do I need to copy an array to use a method on it?](https://stackoverflow.com/questions/53491943/why-do-i-need-to-copy-an-array-to-use-a-method-on-it) – ggorlen Apr 15 '21 at 17:46
  • Probably a better dupe, if anyone has a gold badge: [JavaScript “new Array(n)” and “Array.prototype.map” weirdness](https://stackoverflow.com/questions/5501581/javascript-new-arrayn-and-array-prototype-map-weirdness) – ggorlen Apr 15 '21 at 17:48

1 Answers1

3

You need to fill the array first, before you can map. Just because you designated a size for your array does not mean that the items exist in their positions yet.

new Array(20).fill(null).map(_ => f())

Alternatively, you could call the following:

Array.from(new Array(20), () => f())

or

Array.from({ length: 20 }, f)

There is an extensive list of strategies for creating and manipulating arrays here:

Hacks for Creating JavaScript Arrays

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132