Description
JavaScript provides the built-in Array.prototype.reduce() method that executes a reducer function on each element of the array, resulting in a single output value.
reduce is one of the most powerful array methods because it handles accumulator logic, optional initial values, sparse arrays, and edge-case errors.
In this challenge, you’ll implement your own version of reduce that behaves exactly like the native one.
Your Task
Implement a method Array.prototype.myReduce that:
- Accepts a reducer callback function
- Optionally accepts an
initialValue - Iterates over the array from left to right
- Accumulates a single return value
- Behaves exactly like
Array.prototype.reduce
Example
Input
const nums = [1, 2, 3];
const sum = nums.myReduce((acc, cur) => acc + cur, 0);
console.log(sum);
Output
6More Examples
[1, 2, 3].myReduce((a, b) => a + b);
[1, 2, 3].myReduce((a, b) => a * b, 1);
[, 2, 3].myReduce((a, b) => a + b);
["a", "b", "c"].myReduce((acc, cur) => acc + cur);
Expected Behavior
- Uses
initialValueif provided - If no
initialValue, uses the first defined element - Skips sparse array holes
- Passes
(accumulator, currentValue, index, array)correctly - Throws
TypeErrorfor empty array without initial value - Does not mutate the original array
Constraints
- Do not use
Array.prototype.reduce - Time complexity should be O(n)
- Space complexity should be O(1), excluding call stack