Implement Array.reduce

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.reduce

Approach

Initialize the accumulator to the provided init value (or the first element if omitted, starting iteration from index 1). On each iteration, pass the accumulator and current element to the callback, updating the accumulator with the return value. Return the final accumulator after the loop.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Array Polyfill

Why It Works

Reduce collapses an array into a single value by threading an accumulator through each iteration. The flexibility of the callback allows it to implement sum, max, flatten, groupBy, and nearly any array transformation.

Updated Mar 2026