π 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 methodBut 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