𝗙𝗹𝗮𝘁𝘁𝗲𝗻 𝗡𝗲𝘀𝘁𝗲𝗱 𝗔𝗿𝗿𝗮𝘆𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Nested arrays happen often. You get them in API responses. You see them in tree structures. Flattening turns these into a single list.
Three ways to do this:
- Recursive: Simple to write. Best for small lists.
- Iterative: Uses a stack. Stops stack overflow in deep lists.
- Native flat: Best performance. Use it in modern browsers.
Follow these rules:
- Keep the original array safe.
- Handle empty slots in arrays.
- Set a depth limit.
Pick your tool:
- Simple code: Recursive.
- Large data: Iterative.
- Speed: Native.