Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading