The Array.prototype.flatMap() method is a really useful tool for data manipulation in vanilla JS.

Take a look at the following array of Hogwarts houses:

const houses = [
{
name: 'Gryffindor',
symbol: '🦁',
students: [
'Harry Potter',
'Ron Weasley',
'Hermione Granger'
]
},
{
name: 'Hufflepuff',
symbol: '🦡',
students: [
'Ernie Macmillan',
'Hannah Abbott',
'Susan Bones'
]
},
{
name: 'Ravenclaw',
symbol: '🦅',
students: [
'Luna Lovegood',
'Cho Chang',
'Padma Patil'
]
},
{
name: 'Slytherin',
symbol: '🐍',
students: [
'Draco Malfoy',
'Pansy Parkinson',
'Blaise Zabini'
]
}
];

Now, let's say we want an array of all students, regardless of house:

const students = [
'Harry Potter',
'Ron Weasley',
'Hermione Granger',
'Ernie Macmillan',
'Hannah Abbott',
'Susan Bones',
'Luna Lovegood',
'Cho Chang',
'Padma Patil',
'Draco Malfoy',
'Pansy Parkinson',
'Blaise Zabini'
];

Let's see how the flatMap() method can help us.

The map() method

The first thing we can do is use the map() method to create a new array made up of the inner students arrays:

const students = houses.map(house => house.students);

The new array looks like this:

const students = [
[
'Harry Potter',
'Ron Weasley',
'Hermione Granger'
],
[
'Ernie Macmillan',
'Hannah Abbott',
'Susan Bones'
],
[
'Luna Lovegood',
'Cho Chang',
'Padma Patil'
],
[
'Draco Malfoy',
'Pansy Parkinson',
'Blaise Zabini'
]
];

We're getting there, but the students are still separated by house. We don't want that, so we don't need the inner arrays. We want the student names to be direct elements of the outer students array.

The flat() method

To fix this, we can chain the flat() method. This lets us concatenate the inner arrays into the outer array:

const students = houses.map(house => house.students).flat();

This gives us the desired output, but it's slightly more verbose than necessary.

The flatMap() method

We can actually use the flatMap() method to do this all in one operation:

const students = houses.flatMap(house => house.students);

The MDN Web Docs explain: The flatMap() method ... is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

Learn more: Array.prototype.flatMap() in the MDN Web Docs.

The performance difference is probably negligible, but I love how clean this looks! ❤️