DEV Community

Lucas Stifano
Lucas Stifano

Posted on • Edited on

Flattening Arrays with flat() and flatMap() in JavaScript

Introduction

Ah, nested arrays, the Matryoshka dolls of the JavaScript world. They're everywhere, hiding layers of data within layers of data. Thankfully, ECMAScript 2019 introduced two new methods, flat() and flatMap(), that make it easier to work with multidimensional arrays. In this article, we'll explore how to use these methods to flatten arrays effectively. Let's get started!

Understanding flat() and flatMap()

In JavaScript, handling nested arrays is a common and often challenging task. To simplify the process of working with multidimensional arrays, we mentioned ECMAScript 2019 introduced two powerful methods: flat() and flatMap(). The flat() method is designed to flatten nested arrays up to a specified depth level, creating a new, single-level array. On the other hand, flatMap() combines the capabilities of both map() and flat(). It first applies a mapping function to each element of the array and then flattens the resulting array up to a depth of 1. By utilizing these two methods, developers can efficiently manipulate and process nested arrays, resulting in cleaner and more readable code.

Using flat()

The flat() method is used to create a new array by recursively flattening the input array up to a specified depth.

Syntax:

array.flat([depth]);
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • depth (Optional): The depth level specifying how deep the input array should be flattened. The default value is 1.

Example:

const nestedArray = [1, [2, [3, [4]], 5]];

const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // Output: [1, 2, [3, [4]], 5]

Enter fullscreen mode Exit fullscreen mode

By default, the flat() method only flattens the input array up to one level deep. To flatten the array up to a specific depth, you can pass the desired depth as an argument:

const nestedArray = [1, [2, [3, [4]], 5]];

const flattenedArray = nestedArray.flat(2);
console.log(flattenedArray); // Output: [1, 2, 3, [4], 5]
Enter fullscreen mode Exit fullscreen mode

To flatten the array completely, you can pass Infinity as the depth:

const nestedArray = [1, [2, [3, [4]], 5]];

const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Real-World Example: Aggregating API Responses

A common use case for flat() in software development is when dealing with data from multiple API endpoints. Often, data from different sources may come in the form of nested arrays that need to be combined into a single array for further processing or display.

Let's assume we have a blog platform, and we want to aggregate the latest blog posts from several authors. We fetch blog post data from different API endpoints, and each response returns an array of blog posts. To combine these arrays and create a single array of blog posts, we can use flat().

Here's an example:

// Simulated API responses containing arrays of blog posts from different authors
const author1Posts = [
  { title: 'JavaScript Best Practices', date: '2023-01-10' },
  { title: 'React vs. Vue', date: '2023-01-15' },
];

const author2Posts = [
  { title: 'Getting Started with Node.js', date: '2023-01-05' },
  { title: 'Express.js for Beginners', date: '2023-01-20' },
];

const author3Posts = [
  { title: 'Demystifying CSS Grid', date: '2023-01-12' },
  { title: 'Responsive Design Techniques', date: '2023-01-18' },
];

// Combine the arrays using flat()
const allPosts = [author1Posts, author2Posts, author3Posts].flat();

console.log(allPosts);

/* Output: [
  { title: 'JavaScript Best Practices', date: '2023-01-10' },
  { title: 'React vs. Vue', date: '2023-01-15' },
  { title: 'Getting Started with Node.js', date: '2023-01-05' },
  { title: 'Express.js for Beginners', date: '2023-01-20' },
  { title: 'Demystifying CSS Grid', date: '2023-01-12' },
  { title: 'Responsive Design Techniques', date: '2023-01-18' }
] */
Enter fullscreen mode Exit fullscreen mode

In this example, we used flat() to combine the arrays of blog posts from different authors into a single, flattened array. This allows us to easily process and display the aggregated blog posts on the platform.

Of course, in a real-world scenario, you would fetch the data from actual API endpoints using techniques such as fetch() or axios, but this example demonstrates how flat() can be effectively used to combine nested arrays into a single array for further processing.

Using flatMap()

The flatMap() method combines the functionality of map() and flat(). It first maps each element using a mapping function, then flattens the resulting array up to a depth of 1. The flatMap() method is particularly useful when you want to process and flatten elements in a single step.

Syntax:

array.flatMap(mappingFunction);
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • mappingFunction: A function that produces an element of the new array, taking three arguments: the current element's value, the current element's index, and the array being traversed.

Example:

const array = [1, 2, 3, 4];

const flattenedArray = array.flatMap((value) => [value, value * 2]);
console.log(flattenedArray); // Output: [1, 2, 2, 4, 3, 6, 4, 8]
Enter fullscreen mode Exit fullscreen mode

In this example, the flatMap() method processes each element of the input array and returns a new array containing the original value and the doubled value. The resulting array is flattened by default.

Real-World Example: Search Autocomplete Suggestions

One common use case for flatMap() is in search autocomplete functionality, where we need to generate a list of suggested search terms based on the user's input. This often involves processing and combining data from multiple sources, such as popular search terms, user search history, and related search terms.

Let's say we have an e-commerce website and want to provide autocomplete suggestions for our search bar. We have three different data sources:

  1. Popular search terms
  2. User's search history
  3. Related search terms based on the user's input

We need to process each data source, generate an array of suggestions, and then flatten the final array to display the suggestions.

Here's an example of how we can use flatMap() to achieve this:

const popularSearchTerms = ['laptop', 'smartphone', 'headphone'];
const userSearchHistory = ['tablet', 'touchscreen'];
const relatedSearchTerms = ['mouse', 'keyboard'];

// Function to process search terms and generate suggestions
const processSearchTerms = (term) => {
  // In a real-world scenario, more complex logic would be applied to generate suggestions
  // For this example, we'll simply return the term and its plural form
  return [term, `${term}s`];
};

// Combine and process search terms using flatMap()
const searchSuggestions = [
  ...popularSearchTerms,
  ...userSearchHistory,
  ...relatedSearchTerms,
].flatMap(processSearchTerms);


console.log(searchSuggestions);

// Output: [
//   'laptop', 'laptops', 'smartphone', 'smartphones', 'headphone', 'headphones',
//   'tablet', 'tablets', 'touchscreen', 'touchscreens',
//   'mouse', 'mouses', 'keyboard', 'keyboards'
// ]
Enter fullscreen mode Exit fullscreen mode

In this example, we used flatMap() to process each search term from the combined array and generate an array of suggestions. The final searchSuggestions array is flattened, making it suitable for displaying autocomplete suggestions in the search bar.

Of course, this is a simplified example, and in a real-world scenario, the processing logic would be more complex, and the generated suggestions would be more relevant. Nonetheless, it demonstrates how flatMap() can be effectively used to process and combine data from multiple sources into a flattened array.

Conclusion

And there you have it! Our newfound friends flat() and flatMap() have proven themselves to be the dynamic duo of JavaScript array manipulation. These methods are powerful tools for working with nested arrays in JavaScript. They allow you to flatten arrays up to a specified depth and simplify the process of mapping and flattening simultaneously. By understanding and using these methods, you can write cleaner, more efficient code when working with multidimensional arrays. Happy coding!

Top comments (1)

Collapse
 
yaizacanopoli profile image
Yaiza Canopoli

Just came across this post when searching for a breakdown of the topic. Thanks for the clear explanation! Just a note, I think the example with the popular search terms would be easier to understand if the original items in the arrays weren't already plural :)