Home > Back-end >  Create N length of array with values
Create N length of array with values

Time:11-10

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:

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

CodePudding user response:

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}`);
  • Related