8 April 2024

array-method-flatMap image

JavaScript Array Methods: Understanding `flatMap`

The flatMap method is a powerful tool in JavaScript that combines the functionality of both map and flat, allowing for the transformation and flattening of array elements in a single step. Let's delve into how this method works and explore its practical applications.

Simple Example

Consider the following example that demonstrates the basic use of flatMap:

const arr = [
  [1, 2],
  [3, 4],
  [5, 6],
].flatMap((n) => n)
console.log(arr) // [1, 2, 3, 4, 5, 6]

This method is particularly useful when we need both the mapping and flattening of an array, but why not just use map followed by flat? The answer lies in efficiency; flatMap is slightly more efficient than calling map and flat separately.

Moreover, flatMap can serve as a viable alternative to the reduce method in certain scenarios.

Practical Application

Let's examine a more complex example involving an array of recent user orders, where each order includes details such as the date, total price, and a list of products:

// Recent orders
const recentOrders = [
  {
    date: '06.04.2024',
    totalPrice: 18,
    products: [
      { name: 'milk', amount: 1, price: 6 },
      { name: 'fruits', amount: 4, price: 12 },
    ],
  },
  {
    date: '05.04.2024',
    totalPrice: 30,
    products: [
      { name: 'eggs', amount: 4, price: 20 },
      { name: 'apples', amount: 2, price: 10 },
    ],
  },
]

Our goal is to extract and display only the products from these recent orders. While this can be achieved using the reduce method, flatMap offers a more concise solution:

Using reduce:

const recentProducts = recentOrders.reduce((acc, item) => {
  acc.push(...item.products)
  return acc
}, [])
console.log(recentProducts)
// Output:
// [
//   {name: 'milk', amount: 1, price: 6},
//   {name: 'fruits', amount: 4, price: 12},
//   {name: 'eggs', amount: 4, price: 20},
//   {name: 'apples', amount: 2, price: 10},
// ]

Using flatMap:

const recentProducts = recentOrders.flatMap((item) => item.products)
console.log(recentProducts)
// Output:
// [
//   {name: 'milk', amount: 1, price: 6},
//   {name: 'fruits', amount: 4, price: 12},
//   {name: 'eggs', amount: 4, price: 20},
//   {name: 'apples', amount: 2, price: 10},
// ]

The flatMap approach is not only simpler but also enhances code readability.

In conclusion, for tasks requiring the straightforward combination of mapping and flattening, flatMap should be your go-to choice. For more complex transformations, consider sticking with the reduce method.

Thanks for hanging out! 👋