The flatMap() method in JavaScript is used to both flatten and map elements of an array. It takes a callback function as an argument, which is applied to each element of the array, and the results are then flattened into a new array.
- It's a method that combines mapping and flattening an array in a single step.
- It applies a function to each element of an array, creating new arrays for each element.
- It then flattens the resulting arrays into a single, one-dimensional array.
- It doesn't modify the original array.
- It creates a new array as the output.
- It's often more efficient than using map() followed by flat().
const students = [ { firstName: "Alice", lastName: "Johnson" }, { firstName: "Bob", lastName: "Smith" } ]; const fullNames = students.flatMap(student => [student.firstName+" "+student.lastName]); console.log(fullNames); //["Alice Johnson", "Bob Smith"]
Explanation:
- flatMap() applies the function to each student object.
- The function extracts the firstName and lastName and creates an array with both.
- flatMap() flattens the resulting arrays into a single array of full names.
const banks = ["Bank of America", "Chase", "Wells Fargo"]; const cities = ["New York", "San Francisco", "Los Angeles"]; const bankBranches = banks.flatMap(bank => cities.map(city => ({ bank, city }))); console.log(bankBranches); // Output: [{ bank: "Bank of America", city: "New York" }, ... ]
Explanation:
- flatMap() creates objects representing bank branches in each city.
- It maps cities.map() to each bank, creating nested arrays of objects.
- It flattens them into a single array of bank branch objects.
let forest = [ ['pine', 'oak'], ['maple', 'cedar'], ['cherry', 'birch'] ]; let trees = forest.flatMap(area => area); console.log(trees); // Output: ['pine', 'oak', 'maple', 'cedar', 'cherry', 'birch']
Suppose we have an array representing a forest, where each element is an array of trees. We want to flatten this into a single array of trees.
const companies = [ { name: 'CompanyA', employees: ['Employee1', 'Employee2'] }, { name: 'CompanyB', employees: ['Employee3', 'Employee4'] }, ]; const allEmployees = companies.flatMap(company => company.employees.flatMap(employee => `${company.name}: ${employee}`)); console.log(allEmployees);
Explanation:
In this example, we have an array of company objects with names and arrays of employees. The flatMap() method is used to map each employee to a formatted string that includes the company name.
The result will be ['CompanyA: Employee1', 'CompanyA: Employee2', 'CompanyB: Employee3', 'CompanyB: Employee4'].
In summary, flatMap() is a powerful method that combines mapping and flattening, making it useful for scenarios where you want to transform and flatten arrays simultaneously.