Flattening Arrays in JavaScript

Hero image for Flattening Arrays in JavaScript. Image by Chris Robert.
Hero image for 'Flattening Arrays in JavaScript.' Image by Chris Robert.

Working with nested arrays is common in JavaScript, especially when dealing with complex data structures around booking systems or ecommerce for example. 'Flattening' an array is the process of converting a multidimensional nested array into a singledimensional one.

In this article, I intend to explore various methods for flattening arrays in JavaScript, from modern builtin approaches to older techniques. Hopefully, you will understand how to handle different levels of nested arrays efficiently by the end.


What Does It Mean to Flatten an Array?

Starting with the basics, flattening an array involves converting nested arrays into a single, flat array containing all the elements. For example:

const nestedArray = [1, [2, [3, [4, 5]]], 6];// Flattened versionconst flatArray = [1, 2, 3, 4, 5, 6];

Using Array.prototype.flat()

The simplest way to flatten arrays in modern JavaScript is with the .flat() method, introduced in ECMAScript 2019 (ES10).

Basic Usage

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

However, by default, .flat() only flattens the array one level deep.

Flattening Deeper Arrays

To flatten arrays with deeper nesting, you can specify the depth as an argument. For example:

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

Or, if you want to flatten to an infinite depth, you can quite literally pass Infinity in:

const fullyFlattened = deepNestedArray.flat(Infinity);console.log(fullyFlattened);  // Output: [1, 2, 3, 4, 5, 6]

When .flat() Might Not Be Available

The web moves fast, and 2019 wasn't all that long ago, so there's a chance that it may not be supported in your browser support matrix, especially if you're still targeting IE11. In those situations, alternative methods would be required.


Flattening Arrays Without .flat()

Using Recursion

As you might have already guessed, a classic approach to flattening arrays would be to use recursion like this:

const flattenArray = (arr: any[]): any[] =>  arr.reduce((acc, val) =>    Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []  );const nestedArray = [1, [2, [3, [4, 5]]], 6];console.log(flattenArray(nestedArray));   // Output: [1, 2, 3, 4, 5, 6]

The method in this example checks if each element is an array. If so, it recursively flattens it; otherwise, it adds the element to the accumulator.

Using a Stack

If not recursion, then we can achieve the same thing with another method which involves an iterative approach with a stack:

const flattenUsingStack = (arr: any[]): any[] => {  const stack = [...arr];  const result: any[] = [];  while (stack.length) {    const next = stack.pop();    if (Array.isArray(next)) {      stack.push(...next);    } else {      result.push(next);    }  }  return result.reverse();};const nestedArray = [1, [2, [3, [4, 5]]], 6];console.log(flattenUsingStack(nestedArray));  // Output: [1, 2, 3, 4, 5, 6]

With this approach, we can avoid recursion, which can be beneficial for very large arrays that might otherwise cause stack overflow errors with recursive solutions.


Performance Considerations

  • .flat() is optimised in modern JavaScript engines and is generally the fastest and cleanest solution for supported environments.
  • Recursive functions are concise but may suffer from performance issues with deeply nested or larger arrays.
  • Stackbased approaches handle large datasets better without risking stack overflow errors.

When performance is critical, I would advise benchmarking different methods with your specific data to determine which solution works best.


Wrapping up

Flattening arrays in JavaScript can be straightforward with modern methods like .flat(), but older techniques such as recursion and stackbased approaches are invaluable for compatibility and understanding the underlying principles.

Key Takeaways

  • The .flat() method (introduced in ES10) is the simplest way to flatten arrays.
  • Use .flat(Infinity) to flatten arrays with arbitrary nesting levels.
  • Recursive and stackbased methods provide compatibility for environments where .flat() isn't supported.
  • Choose the right method based on browser support requirements and data complexity.

Understanding these techniques will help you choose the right approach for array flattening, no matter the JavaScript environment you're working with.


Categories:

  1. Development
  2. Front‑End Development
  3. Guides
  4. JavaScript