All questions

Array.prototype.myReduce

Premium

Array.prototype.myReduce

You're totalling a list of transaction amounts to compute a running balance, or folding a list of words into a frequency map, or turning an array of { id, value } objects into a lookup by id. Each of these is the same shape: walk the array once, carry a result forward, return whatever ends up in your hand. That's reduce.

Array.prototype.reduce is a way of "reducing" elements in an array by calling a "reducer" callback function on each element of the array in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

Implement Array.prototype.reduce. To avoid overwriting the actual Array.prototype.reduce (which is being used by the autograder), implement it as Array.prototype.myReduce instead.

Examples

[1, 2, 3].myReduce((prev, curr) => prev + curr, 0); // 6
[1, 2, 3].myReduce((prev, curr) => prev + curr, 4); // 10

Signature

The reducer callback receives four arguments:

arr.myReduce(callback, initialValue?)
// callback(accumulator, currentValue, currentIndex, array)

Notes

There are several nuances to Array.prototype.reduce — read the MDN spec before attempting.

Highlights you must get right:

  • No initialValue, non-empty array → the accumulator starts at this[0] and iteration begins at index 1.
  • No initialValue, empty array → throw a TypeError.
  • initialValue provided, empty array → return the initialValue unchanged (callback never runs).
  • Sparse arrays — skip holes ([1, , 3] has a hole at index 1). myReduce must NOT invoke the callback for missing indices.
  • The callback receives (accumulator, currentValue, currentIndex, array). Pass this as the fourth argument.
  • Iterate over the array's length at the start of the call — additions or deletions during iteration must not be picked up.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium