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

240
Views
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
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!