πŸš€ 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