Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda