Implement Array.flatMap

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Implement Array.flatMap

Approach

Apply the callback to each element (like map), then flatten the result by one level. If the callback returns an array, spread its elements into the result; if it returns a non-array value, push it directly. This combines mapping and flattening in a single pass.

Complexity Analysis

Time
O(n * m)
Space
O(n * m)

Pattern

Array Polyfill

Why It Works

FlatMap is equivalent to map followed by flat(1) but more efficient as it does both in one iteration. It is ideal when each input element maps to zero, one, or multiple output elements.

Updated Feb 2026