Flatten Multi-Dimensional Array with Depth Control in JavaScript

🚀 Day 26/30 – Flatten a Multi-Dimensional Array (Depth Controlled) 🧠 📌 Problem Given: A multi-dimensional array arr An integer depth n Return a flattened version of arr. Rules: The array may contain integers or nested arrays Only flatten elements if current depth < n Depth of first-level elements = 0 Do NOT use Array.flat() 🧠 Example 1 arr = [1, [2, [3, 4]], 5] n = 1 Output: [1, 2, [3, 4], 5] 🧠 Example 2 arr = [1, [2, [3, 4]], 5] n = 2 Output: [1, 2, 3, 4, 5] 💡 JavaScript Solution (Recursive Approach) var flat = function(arr, n) { const result = []; function flatten(current, depth) { for (let item of current) { if (Array.isArray(item) && depth < n) { flatten(item, depth + 1); } else { result.push(item); } } } flatten(arr, 0); return result; }; 🔎 Why This Works We track depth Only flatten when depth < n Recursion handles unlimited nesting Preserves element order Time Complexity: O(total elements) Space Complexity: O(total elements + recursion stack) 🧠 What This Teaches ✅ Recursion fundamentals ✅ Depth tracking ✅ Tree-like traversal ✅ Controlling execution scope ✅ How Array.flat() actually works internally ⚡ Real-World Use Cases Normalizing API responses Parsing nested JSON Flattening comment threads Handling deeply nested UI state Transforming hierarchical data #JavaScript #30DaysOfJavaScript #CodingChallenge #Recursion #DataStructures #Algorithms #FrontendDevelopment #WebDevelopment #LearnToCode #SoftwareEngineering #ProblemSolving #TechCommunity #InterviewPrep #100DaysOfCode #JSDeveloper JavaScript flatten array without flat Recursive array flattening JS Flatten array with depth JavaScript Implement Array.flat manually JavaScript recursion interview question Multi-dimensional array flatten JS Depth controlled flattening JavaScript Advanced JavaScript problem solving

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories