🪆 Flattening Arrays in JavaScript — The Complete Visual Guide
Imagine a Russian nesting doll. You open one, find another. Open that, find another. That's a nested array. Our job? Unpack them all into one flat row.
📦 What Are Nested Arrays?
A nested array is simply an array that contains other arrays as its elements. Arrays inside arrays. Boxes inside boxes.
// Simple flat array const flat = [ 1 , 2 , 3 , 4 , 5 ];
// Nested array — arrays inside arrays const nested = [ 1 , [ 2 , 3 ], [ 4 , [ 5 , 6 ]], [[[ 7 ]]]];
Enter fullscreen mode
Exit fullscreen mode
Visualizing the layers:
[1, [2, 3], [4, [5, 6]], [[[7]]]] ^ ^^^^^ ^^^^^^^^^^ ^^^^^^ | | | | | depth 1 depth 1+2 depth 1+2+3 depth 0 (top level)
Enter fullscreen mode
Exit fullscreen mode
These show up all the time in real code:
🌐 API responses — deeply nested JSON objects
🗃️ Database results — grouped or paginated data
📁 File system trees — folders containing folders
🧮 Matrix math — rows and columns
🗺️ Category trees — parent/child…