Code Snippets - Pre-populate an array in JavaScript
This is the second post I write about code snippets I find useful (you can check the first one here). And today's code snippet is how to pre-populate an array in JavaScript.
The for
loop is probably one of the first choices that comes to mind when dealing with arrays or collections.
But instead, I prefer to create an array with Array.from.
If you've never heard of Array.from
before, it accepts and array-like or an iteratable object as its first argument so we can map into it.
Once the array is created, map
gives us each element in the newly created array so we can populate it with, for example, the index of each element.
function createArray(size: number) {
return Array.from({ length: size }).map((_, index) => index + 1)
}
or using the Array constructor:
function createArray(size: number) {
return Array.from(Array(size)).map((_, index) => index + 1)
}
I hope that's helpful and interesting to you. 👋🏼
Did you know you can help me with this page?
If you see something wrong, think this page needs clarification, you found a typo or any other suggestion you might have feel free to open a PR and I will take care of the rest.
My entire site is available to edit on GitHub and all contributions are very welcome 🤙🏼.
Hemerson Carlin, also known as mersocarlin, is passionate and resourceful full-stack Software Engineer with 10+ years of experience focused on agile development, architecture and team building.
This is the space to share the things he likes, a couple of ideas and some of his work.