Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sejalkailashyadav/2bff48154531fc7420d022df86e72e71 to your computer and use it in GitHub Desktop.
Save sejalkailashyadav/2bff48154531fc7420d022df86e72e71 to your computer and use it in GitHub Desktop.

real-world data to show the difference between using map().flat() and flatMap().


Scenario: A List of Orders and Items

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.

1. Using map() and flat()

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.

2. Using flatMap()

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.

Key Differences:

  • 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, while map().flat() requires two operations (first creating a nested array with map(), then flattening it with flat()).

Summary:

  • 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().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment