Implement Array.reduce (Medium)

Good morning! Here's our prompt for today.

In JavaScript there is a built-in method called reduce() that can be used over the Array prototype. What this method does, is that it executes a user-supplied "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.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

The easiest to understand case for reduce() is to return the sum of all the elements in an array:

JAVASCRIPT
1const array1 = [1, 2, 3, 4];
2
3// 0 + 1 + 2 + 3 + 4
4const initialValue = 0;
5const sumWithInitial = array1.reduce(
6  (previousValue, currentValue) => previousValue + currentValue,
7  initialValue
8);
9
10console.log(sumWithInitial);
11// expected output: 10

Can you implement your own version of this method?

Question

JAVASCRIPT
OUTPUT
Results will appear here.