real-world data to show the difference between using map().flat()
and flatMap()
.
You have an array of orders, and each order contains an array of items. You want to flatten the items from all orders into a single list.
const orders = [
{ orderId: 1, items: ['Apple', 'Banana'] },
{ orderId: 2, items: ['Orange', 'Grapes'] },
{ orderId: 3, items: ['Mango', 'Pineapple'] }
];
// Step 1: Use map() to get all items in each order
const itemsMapped = orders.map(order => order.items);
// Step 2: Use flat() to flatten the array of arrays
const allItems = itemsMapped.flat();
console.log(allItems);
// Output: ["Apple", "Banana", "Orange", "Grapes", "Mango", "Pineapple"]
- Explanation:
map()
creates an array of arrays of items.flat()
flattens that array by one level.
const orders = [
{ orderId: 1, items: ['Apple', 'Banana'] },
{ orderId: 2, items: ['Orange', 'Grapes'] },
{ orderId: 3, items: ['Mango', 'Pineapple'] }
];
// Using flatMap directly
const allItems = orders.flatMap(order => order.items);
console.log(allItems);
// Output: ["Apple", "Banana", "Orange", "Grapes", "Mango", "Pineapple"]
- Explanation:
flatMap()
maps over each order and automatically flattens the array of items in one pass.
- Code Simplicity:
flatMap()
combines both mapping and flattening into one simple operation. - Performance:
flatMap()
is more efficient because it performs the map and flattening in a single step, whilemap().flat()
requires two operations (first creating a nested array withmap()
, then flattening it withflat()
).
- If you're working with arrays of objects where each object has an array inside it, and you want to flatten the results, use
flatMap()
. - If you need to map first and then flatten in two separate steps, use
map().flat()
.