1

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('') );
vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80
  • 2
    See the linked answers. Basically: `console.log(Array.from(arr, e => e ? e.a : "-"));` – T.J. Crowder Feb 21 '22 at 13:42
  • @T.J.Crowder I Am not sure, but I think not really as the question is quite specific about the content and expected output of the array. However one answer suggests a `mapx` function that essentially would fit the "obvious handcrafted loop"-condition. – vlad_tepesch Feb 21 '22 at 13:46
  • [This answer](https://stackoverflow.com/a/63108226/157247) shows using `Array.from`'s mapping callback. Remember that on SO, it's not whether the *question* is the same, but whether the *answers* are applicable. – T.J. Crowder Feb 21 '22 at 13:48
  • 1
    @T.J.Crowder thank you to pointing me to that `Array.from`. I actually filtered this answer mentally after reading the `fill` function because it does not seemt to fit at all. – vlad_tepesch Feb 21 '22 at 13:58
  • I've been trying to get used to the reduce method lately, I'm thinking of trying such a solution if I have such a problem. `let r = [...arr].reduce((newArr,currentItem)=>{ let tempItem; if(typeof currentItem === "undefined"){ tempItem = "-"; }else{ tempItem = currentItem.a; } newArr.push(tempItem); return newArr; },[]); console.log(r)` – huzeyfetas Feb 21 '22 at 13:59
  • Yeah, that''s easy to do! I've added some others that cover the ground a bit better IMHO (but I would think that, I've posted answers to them -- one now, one previously :-) ). – T.J. Crowder Feb 21 '22 at 14:00
  • so just for the records: the most elegant way to do this imho would look like; `console.log(Array.from(arr, e => e?e.a:'-').join(''));` – vlad_tepesch Feb 21 '22 at 14:07

0 Answers0