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;
4
Answers
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.
Or:
A slight mistake. You’re returnng the the sublist here. But you should return mapped sublist.
Actually this two are not the same:
.map
function return new array with mapped data, and does not mutate original array.So, in order to make this two examples work identically you need to store result of .map() to a variable and return it. Like so:
Your first function will do the same job if you return the new array created using map