flatMap is used to flatten an array of arrays into a single array.
map simply converts one array to an other array. For example, suppose you have a list of person objects like this:
const friends = [
{name: 'Dave', kids: ['Max', 'Jack']},
{name: 'Max', kids: ['Sam', 'Alex', 'Megan']},
{name: 'Jordan', kids: ['Mason', 'Cameron', 'Kaylin']}
];
But what you really need is an array of person names (i.e. strings: [“Dave”, “Max”, “Jordan”]). To convert this array of person object to array of strings, you would first define your mapping function like this:
const mapFunction = p -> p.name;
Then, use array.map like this:
const names = friends.map(mapFunction);
which returns:
["Dave", "Max", "Jordan"]
flatMap is similar to map in that you are converting one array into another array. But there are a few subtle differences:
First of all, map is generally a one-to-one thing. The mapping function takes one object in and returns one object out:
p -> p.name
This means that 3 person objects in will produce 3 names out.
flatMap, on the other hand, is a one-to-many thing. The mapping function takes one object in but returns an array out:
p -> p.kids
The net result: 3 person objects in will produce 8 kid names out. Thus, this code:
const mapFunction = p -> p.kids;
const kidNames = friends.flatMap(mapFunction);
will return:
["Max", "Jack", "Sam", "Alex", "Megan", "Mason", "Cameron", "Kaylin"]