Flatten nested array recursively | Array.flat() in JavaScript

Flatten nested array recursively | Array.flat() in JavaScript

Hey everyone, Today I’ll be discussing flattening arrays which were always complicated in JavaScript but not anymore! I’m going to explain how to use the new array methods introduced in ES2019 — flat()

We will see multiple ways to flatten arrays and even depth-level arrays using Array.prototype.flat()and recursive way.

Let’s start going through a few examples to understand the scenarios.


Ways to flatten array

  • Usingflat() method

  • Using recursion

  • Using generator function

Using Array.prototype.flat() method

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const hearts = ["💜",["💙"],["❤️‍🩹"]];
const flattened = heart.flat();
console.log(flattened);   // ['💜', '💙', '❤️‍🩹']

Setting depth parameter

flat() will only flatten one layer deep by default.

// Default 1
hearts.flat();  // ['💜', '💙', '❤️‍🩹']

// Same as
hearts.flat(1); // ['💜', '💙', '❤️‍🩹']

Flattening nested arrays

By passing parameter depth

using depth parameter

Infinitely Nested Arrays(*Infinity*)

nested array

Flattening sparse(empty spaces) arrays using flat()

The flat() method removes empty slots in arrays:

sparse array

Browser compatibility

Using Recursion

1. Using Array.prototype.concat() and Array.prototype.reduce() function

2. Iterative way

Using the generator function

Another way using a generator function for flattening nested arrays. The following code example shows how to implement this using the Array.isArray() method.

That’s all. Thanks for reading ❤. You can find the full code on GitHub.

Say Hello! Twitter | Blog | LinkedIn | Github