Flattening Arrays with JavaScript Recursion

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of flattening an array up to a specified depth using JavaScript. We will learn how to use recursion, reduce, and concat methods to merge elements or arrays. By the end of this lab, you will be able to efficiently flatten arrays and manipulate nested data structures in JavaScript.


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`") subgraph Lab Skills javascript/variables -.-> lab-28311{{"`Flattening Arrays with JavaScript Recursion`"}} javascript/data_types -.-> lab-28311{{"`Flattening Arrays with JavaScript Recursion`"}} javascript/arith_ops -.-> lab-28311{{"`Flattening Arrays with JavaScript Recursion`"}} javascript/comp_ops -.-> lab-28311{{"`Flattening Arrays with JavaScript Recursion`"}} javascript/higher_funcs -.-> lab-28311{{"`Flattening Arrays with JavaScript Recursion`"}} end

How to Flatten an Array with JavaScript

To flatten an array up to a specified depth in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the flatten function with two arguments: arr (the array to be flattened) and depth (the maximum number of nested levels to be flattened).
  3. Inside the flatten function, use recursion to decrement depth by 1 for each level of depth.
  4. Use Array.prototype.reduce() and Array.prototype.concat() to merge elements or arrays.
  5. Add a base case for when depth is equal to 1 to stop the recursion.
  6. Omit the second argument, depth, to flatten only to a depth of 1 (single flatten).

Here is the code for the flatten function:

const flatten = (arr, depth = 1) =>
  arr.reduce(
    (a, v) =>
      a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
    []
  );

You can test the flatten function with the following examples:

flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]

Summary

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

Other JavaScript Tutorials you may like