Loading workspace…

Array.prototype.reduce

Languages

Array.prototype.reduce is a way of "reducing" elements in an array by calling a "reducer" callback function on each element in order and passing along the return value from the previous callback. 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.

Examples

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

Notes

There are some nuances in how Array.prototype.reduce works and what values are passed to the reducer callback. Read the specification for Array.prototype.reduce on MDN Docs before attempting.

Changelog

  1. Inherited array indexes

    The grader checks that inherited indexes participate in the reduction, including when the initial accumulator comes from the array.

  2. Accumulator and sparse arrays

    The grader checks that an explicit undefined initial value is used as supplied. Without an initial value, leading holes are skipped and an array containing only holes throws.

  3. JavaScript starter return type

    The starter documents the return value as the accumulator’s type. A reduction can return a single value of any supported type.