Flatten Nested Arrays with JavaScript Recursion

🚀 Day 14/100 – Implementing a "flattenArray" Function (JavaScript) Today I solved a common JavaScript problem: Flattening a nested array. --- 🧠 Problem: Given a nested array, return a single-level array containing all the elements. Example: Input: [1, 2, [3, 4], [5, [6, 7]]] Output: [1, 2, 3, 4, 5, 6, 7] --- ✅ Solution (Using Recursion): function flattenArray(arr) { const result = []; for (let item of arr) { if (Array.isArray(item)) { result.push(...flattenArray(item)); } else { result.push(item); } } return result; } const arr = [1, 2, [3, 4], [5, [6, 7]]]; console.log(flattenArray(arr)); // Output: [1,2,3,4,5,6,7] --- 💡 Key Learning: - Recursion helps solve nested data problems - "Array.isArray()" checks whether a value is an array - Spread operator ("...") helps merge results --- 📌 Time Complexity: O(n) – Every element is processed once. 📌 Space Complexity: O(n) – For the result array. --- 🧠 Why This Matters? Flattening arrays is useful in: - Data transformation - Handling nested API responses - Building utility functions - JavaScript interview questions --- I’m currently open to Frontend Developer opportunities (React / Next.js) and available for immediate joining. 📩 Email: bantykumar13365@gmail.com 📱 Mobile: 7417401815 If you're hiring or know someone who is, feel free to connect. #OpenToWork #FrontendDeveloper #JavaScript #ReactJS #NextJS #ImmediateJoiner #100DaysOfCode

To view or add a comment, sign in

Explore content categories