Search code examples
javascriptarrow-functions

flatMap with one line of arrow function confusion


The first arrow function in flatMap does not get me what I need, the second arrow function does. I need to turn data into the flat name array ['John', 'Jane', 'Bob']

const data = [
    [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }],
    [{ name: 'Bob', age: 40 }]
    ];
    
let mappedData = data.flatMap(sublist => {
    sublist.map(person => person.name)
    return sublist
})

console.log(mappedData);


mappedData = data.flatMap(sublist => 
    sublist.map(person => person.name)
)
console.log(mappedData);

But why ? I had thought these two arrow function are the same, the second arrow function just remove the body braces and word "return" — the return is implied.

The following two arrow function are the same. Then why does my two arrow function in flatMap do not give the same result ?

(a) => {
  return a + 100;
};

// 2. Remove the body braces and word "return" — the return is implied.
(a) => a + 100;

Solution

  • sublist => {
        sublist.map(person => person.name)
        return sublist
    }
    

    The above code calls .map, creating a new array, but then does nothing with that array. Afterwards, it returns the original un-mapped list.

    If you want this code to behave the same as the second code example, then you want to return the mapped array.

    sublist => {
      const newArray = sublist.map(person => person.name);
      return newArray;
    }
    

    Or:

    sublist => {
      return sublist.map(person => person.name);
    }