๐ 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