Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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:

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}`);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!