Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create N length of array with values

I am creating a N length array with value filled in, I am looking if I can improve the way I am doing it.

I get random number on the fly to determine the number of array item.

What I am doing is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example, if the number is 5.

let array = [];

for (let i = 1; i <= 5; i++) {
  array.push(`item0${i}`)
}

Now, the array will be [‘item01’, ‘item02, …. ‘item05’]

This looks quite long, can this be done is a shorter way?

Thanks

>Solution :

Simply use the new Array Constructor.

const arr = new Array(5)

This however will only create an array of length 5 without any entries. To use array methods on the array, you will first have to either fill the array with valus, or create entries of value undefined using the spread syntax.

If you want to pre-populate the array:

function makeArray(n) {
    return (new Array(n)).fill().map((el,ind) => `item0${ind}`)
}

makeArray(5);

Or even provide a callback as property so you can change what the pre-filled elements look like and use spread syntax to avoid the .fill() call:

function makeArray(n, cb) {
    return [...new Array(n)].map((el,ind) => cb(ind))
}

makeArray(5, (ind) => `item0${ind}`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading