Imagine you're building a shopping cart app. Users add items like ["apple", "banana", ["orange", ["grape", "kiwi"]]] . Suddenly, your loops break because of those sneaky nested arrays. Frustrating, right?
Array flattening turns this mess into a simple ["apple", "banana", "orange", "grape", "kiwi"] . In this blog, we'll demystify nested arrays, explore why flattening matters, break down approaches step-by-step, and tackle real interview scenarios—including a custom polyfill you can steal (or improve).
What Are Nested Arrays?
Nested arrays are arrays containing other arrays as elements within it.
Original Nested Array: [ 1 , [ 2 , 3 ], [ 4 , [ 5 , 6 ], 7 ], 8 ]
Enter fullscreen mode
Exit fullscreen mode
Think of it like a filing cabinet: top-level folders hold documents and sub-folders.
Why Flatten Arrays win in Real-world scenarios?
Flattening simplifies data for:
Iteration : Loop once without if (Array.isArray(item)) checks.
Processing : Easier sorting, filtering, or mapping on flat lists.
UI…