Deep Flatten Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to deep flatten an array in JavaScript. We will use recursion and the Array.prototype.concat() method along with the spread operator to flatten an array. By the end of the lab, you will be able to write a function that can deeply flatten an array of any depth.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28262{{"`Deep Flatten Array`"}} javascript/data_types -.-> lab-28262{{"`Deep Flatten Array`"}} javascript/arith_ops -.-> lab-28262{{"`Deep Flatten Array`"}} javascript/comp_ops -.-> lab-28262{{"`Deep Flatten Array`"}} javascript/higher_funcs -.-> lab-28262{{"`Deep Flatten Array`"}} javascript/spread_rest -.-> lab-28262{{"`Deep Flatten Array`"}} end

How to Deep Flatten an Array using Recursion in JavaScript

To deep flatten an array in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use recursion to flatten the array.
  3. Use the Array.prototype.concat() method with an empty array ([]) and the spread operator (...) to flatten the array.
  4. Recursively flatten each element that is an array.
  5. Implement the following code:
const deepFlatten = (arr) =>
  [].concat(...arr.map((v) => (Array.isArray(v) ? deepFlatten(v) : v)));

deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]

By following these steps, you can easily deep flatten an array using recursion in JavaScript.

Summary

Congratulations! You have completed the Deep Flatten Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like