Skip to main content

Array

๐Ÿš€ Frontend DSA 3 - ๐Ÿ” How to Flatten a Nested Array in JavaScript up to a Given Depth

Working with deeply nested arrays in JavaScript can be tricky, especially when you want to flatten them to a specific depth. Thankfully, you can build your own custom array flattener with just a few lines of code! ๐Ÿงฉ

In this tutorial, weโ€™ll break down how to flatten a nested array up to a certain depth using recursion and some smart logic in JavaScript. ๐Ÿ“š


๐ŸŽฏ What You'll Learn

  • What array flattening means ๐Ÿงฑ
  • How to flatten an array up to a given depth ๐Ÿ“
  • JavaScript recursive techniques ๐ŸŒ€
  • Practical use cases with sample inputs & outputs ๐Ÿ’ก

๐Ÿ“ฆ Problem Statement

Given a nested array like:

let arr = [1, 2, [3, [4, [5, 6]]], 7, 8];

We want to flatten it up to a given depth. For example:

  • flattenArray(arr, 1) should return โžก๏ธ [1, 2, 3, [4, [5, 6]], 7, 8]
  • flattenArray(arr, 2) should return โžก๏ธ [1, 2, 3, 4, [5, 6], 7, 8]
  • flattenArray(arr, 3) should return โžก๏ธ [1, 2, 3, 4, 5, 6, 7, 8]

๐Ÿ› ๏ธ JavaScript Code with Explanation

// ๐Ÿš€ Flatten an array up to a given depth
const flattenArray = (inputArray, depth = 1) => {
  // Base case: no more depth to flatten
  if (depth === 0) {
    return inputArray;
  }

  const finalAnswer = [];

  for (let i = 0; i < inputArray.length; i++) {
    const currentValue = inputArray[i];

    if (Array.isArray(currentValue)) {
      // If current value is an array, flatten it further
      finalAnswer.push(...flattenArray(currentValue, depth - 1));
    } else {
      // If not an array, just push it to the result
      finalAnswer.push(currentValue);
    }
  }

  return finalAnswer;
};

Problem Statement


๐Ÿ”ข Sample Inputs and Outputs

Let's test it with some examples:

โœ… Input 1:

let arr = [1, 2, [3, [4, [5, 6]]], 7, 8];
console.log(flattenArray(arr, 1));

๐Ÿ” Output 1:

[1, 2, 3, [4, [5, 6]], 7, 8]

โœ… Input 2:

console.log(flattenArray(arr, 2));

๐Ÿ” Output 2:

[1, 2, 3, 4, [5, 6], 7, 8]

โœ… Input 3:

console.log(flattenArray(arr, 3));

๐Ÿ” Output 3:

[1, 2, 3, 4, 5, 6, 7, 8]

๐Ÿ’ก JavaScript Notes for Beginners

  • Array.isArray(value) checks whether a value is an array.
  • Recursion is when a function calls itself โ€” a perfect fit for nested structures! ๐ŸŒ€
  • The spread operator (...) is used to unpack elements from one array into another.

๐Ÿง  Why Use Depth-Based Flattening?

Depth-based flattening is super helpful when:

  • You only want to partially flatten data (like from a JSON API or spreadsheet).
  • You need to retain some nesting for later processing.
  • Youโ€™re building utilities or libraries that require flexible flattening.

๐Ÿ“š Bonus Tip: Native .flat() Method

If you're using modern JavaScript (ES2019+), you can also use:

arr.flat(2); // Built-in flat method

But for interview prep or working in environments without .flat(), custom recursion like above is ๐Ÿ’Ž!


๐Ÿ“Œ Final Thoughts

Congratulations! ๐ŸŽ‰ You've just learned how to recursively flatten nested arrays in JavaScript up to any depth you want. This is a must-know pattern for both interviews and real-world development!

๐Ÿง  Tip: Try building your own .flat() polyfill for practice!


Hey there from LearnYard! ๐Ÿ‘‹

Glad to see you exploring the free content from our course! Weโ€™ve shared 10 valuable articles at no cost to help you get a real feel of whatโ€™s inside.

If youโ€™ve found these helpful, weโ€™d love to know! ๐Ÿ’ฌ
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram โ€” and donโ€™t forget to tag Gourav Hammad & Mohammad Fraz. Weโ€™ll personally respond to your post!

Thanks for being part of the LearnYard journey. Keep learning, keep growing! ๐Ÿš€


Loved the free content? Want access to the full course โ€” for free? ๐Ÿ’ธ

Share the course with your friends using your affiliate link (youโ€™ll find it on your profile or home page), and earn 20% commission on each sale.

Just 4โ€“5 sales and youโ€™ll recover the full course price of your course ๐Ÿ”
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! ๐Ÿ› ๏ธ๐Ÿ“ˆ


๐Ÿ“š Keywords for SEO

  • JavaScript Flatten Array to Specific Depth
  • Custom Flatten Function in JavaScript
  • Recursively Flatten Nested Arrays in JavaScript
  • JavaScript Nested Array Flattening Explained
  • Flatten Array Without Using .flat() Method in JS
  • Deep Flattening Arrays in JavaScript
  • Manual Array Flattening JavaScript Example
  • Flatten Multidimensional Arrays in JavaScript
  • Vanilla JS Flatten Function
  • Understanding Array Recursion in JavaScript

๐Ÿ“ข Hashtags for Visibility

#JavaScriptArrays #FlattenArrayJS #CustomJSFunctions #RecursionInJS
#VanillaJavaScript #FrontendInterviewPrep #JSArrayTips #WebDevelopment
#JavaScriptDeepDive #CodeNewbie #FlattenWithoutFlat #LearnJavaScript #FrontendMasters #FunctionalProgrammingJS #JSInterviewPrep #CodingChallenges #NestedArrayFlattening #ArrayRecursion #JSForBeginners #TechLearning