flatMap() Method
The flatMap(callback)
method is similar to the map()
method, but it is used in cases where the result is a multidimensional array that needs to be "flattened".
array.flatMap((element, index, array) => {
// Callback body
});
The students
array contains a list of students with a list of subjects they attend, which is stored in the courses
property. Several students may attend the same subject. You need to make a list of all the subjects attended by this group of students, even repetitive ones.
const students = [
{ name: "Mango", courses: ["mathematics", "physics"] },
{ name: "Poly", courses: ["informatics", "mathematics"] },
{ name: "Kiwi", courses: ["physics", "biology"] },
];
students.map(student => student.courses);
// [['mathematics', 'physics'], ['informatics', 'mathematics'], ['physics', 'biology']]
students.flatMap(student => student.courses);
// ['mathematics', 'physics', 'informatics', 'mathematics', 'physics', 'biology']
It calls a callback for each element of the original array and writes its result to a new array. The difference from map()
is that the new array is "flattened" by one (one nesting). This flattened array is the result of flatMap()
.