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

4

1 Answer 1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.