Array of length 1 is created when using new Array(20)

Viewed 47

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

1 Answers

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

Related