Javascript map question returning an array with empty values

Solution for Javascript map question returning an array with empty values
is Given Below:

I am trying to use .map to create a new array called workspaces that just has the id in the array however the code below whilst the console.log() works fine and shows the id in the console.log as expected when I use the return it doesn’t show these ids in the workspaces array

    const workspaces = this.networkTree.map( (group) => {
      group.units.map( (unit) => {
        console.log(unit.id);   // outputs an id to the console e.g '12345'
        return unit.id;
      });
    });

    console.log(workspaces);   // each array is empty (see image below)

enter image description here

You are missing a return statement:

const workspaces = this.networkTree.map((group) => {
    return group.units.map((unit) => {
        return unit.id;
    });
});

Or, because you are using arrow functions:

const workspaces = this.networkTree.map((group) => group.units.map((unit) => unit.id));

You need to take care to return the result from the nested map, like so:

const workspaces = this.networkTree.map( (group) => {
  return group.units.map( (unit) => { // <= the `return` here
    console.log(unit.id);
    return unit.id;
  });
});

console.log(workspaces);

An alternative would be if you don’t add braces to the inline function:

const workspaces = this.networkTree.map( (group) => 
  group.units.map( (unit) => {
    console.log(unit.id);
    return unit.id;
  })
);

And when you decide to remove the console.log:

const workspaces = this.networkTree.map( (group) => group.units.map( (unit) => unit.id));

I think the reason is that you did not return the new group with the new unit (in the outer map).
You can, for instance, change the braces in the outer map to parentheses for an auto return

const workspaces = this.networkTree.map( (group) => ( // opening (
      group.units.map( (unit) => {
        console.log(unit.id); 
        return unit.id;
      });
    )); // closing )