FrontendPro

3Implement Array.prototype.reduce()

easyAbout 15 minutesCodingarrayspolyfills

Problem

Implement Array.prototype.myReduce(callback, initialValue) so it behaves like the built-in reduce(). It calls callback(accumulator, element, index, array) for every element, from left to right, and returns the final accumulator.

[1, 2, 3].myReduce((sum, n) => sum + n, 0); // 6
[1, 2, 3].myReduce((sum, n) => sum + n); // 6, starts from the first element

Requirements

  • Without an initial value, the first element is the starting accumulator and the loop starts at the next element.
  • An initial value of undefined still counts as "given".
  • Reducing an empty array with no initial value throws a TypeError.
  • Skip holes in sparse arrays.
  • Throw a TypeError when the callback is not a function.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

Javascript Interview Questions ( map, filter and reduce ) - Polyfills and Output Based QuestionsRoadsideCoder on YouTubeOpen on YouTube

Step-by-step

Throw a TypeError when callback is not a function.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever