Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda