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

246
Vistas
javascript also get null and undefined elements on array.map

I have a array that sparsely gets filled with objects. I want to convert the array into something I can log. Unfortunately map just skips the unitialized elements.

let arr = [];

arr[3]  =  {a: 'w'};
arr[7]  =  {a: 'g'};
arr[10] =  {a: 'h'};

arr[20] =  {a: 'q'};

console.log(arr.map(e => e?e.a:'-'));

The output is:

[undefined, undefined, undefined, "w", undefined, undefined, undefined, "g", undefined, undefined, "h", undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "q"]

Is there a way to apply the function to all the elements beside the obvious hand crafted loop?

the output I want to get is:

["-", "-", "-", "w", "-", "-", "-", "g", "-", "-", "h", "-", "-", "-", "-", "-", "-", "-", "-", "-", "q"] 

(to finally join it into a string)

Edit:
According to comments and hints to other questions answer I came up with this solution:

let arr = [];
arr[3]  =  {a: 'w'}; arr[7]  =  {a: 'g'};
arr[10] =  {a: 'h'}; arr[20] =  {a: 'q'};

console.log( Array.from(arr, e => e?e.a:'-').join('') );

about 4 years ago · Juan Pablo Isaza
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