How to Flatten a Nested Array in JavaScript

🧩 SK – Flatten a Nested Array in JavaScript 💡 Explanation (Clear + Concise) A nested array contains other arrays inside it. Flattening means converting it into a single-level array — an essential skill for data manipulation in React, especially when handling API responses or nested JSON data. 🧩 Real-World Example (Code Snippet) // 🧱 Example: Nested array const arr = [1, [2, [3, [4]]]]; // ⚙️ ES6 Method – flat() const flatArr = arr.flat(3); console.log(flatArr); // [1, 2, 3, 4] // 🧠 Custom Recursive Function function flattenArray(input) { return input.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), [] ); } console.log(flattenArray(arr)); // [1, 2, 3, 4] ✅ Why It Matters in React: When API data comes nested, flattening simplifies mapping through UI. Helps manage deeply nested state objects effectively. 💬 Question: Have you ever had to handle deeply nested data structures in your React apps? 📌 Follow Sasikumar S for more daily dev reflections, real-world coding insights & React mastery. 🤝 Connect Now: sasiias2024@gmail.com 💟 Visit: sk-techland.web.app ❤️ Follow our LinkedIn Page for more React & JavaScript growth tips. #JavaScript #ReactJS #ES6 #WebDevelopment #FrontendDeveloper #FlattenArray #JSFundamentals #CodingJourney #CareerGrowth

  • text

To view or add a comment, sign in

Explore content categories