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('') );