Solution

Our solution would be a function that recceives 2 arguments: the callback function, and an initial value (optional).

First, we are going to check if we have passed an empty array without an initial value, and if so, return an error:

JAVASCRIPT
1const argsLength = arguments.length;
2
3if (argsLength === 1 && this.length === 0) {
4  throw new Error();
5}

Then we are going to define our initial index, and initial result value - based on our argsLength. So, our initial result value will be the initialValue if any supplied, or otherwise it will be the return value of the previous calculation.

JAVASCRIPT
1let  index  =  argsLength  ===  1  ?  1  :  0;
2let  resultValue  =  argsLength  ===  1  ?  this[0] :  initialValue;

Then, in a for loop, we are going to call the callback function with the adequate parameters (current result value, the currently looped array element, its index, and the array itself). The return value of the callback function will be our new result value.

JAVASCRIPT
1for (let i = index; i < this.length; i += 1) {
2  resultValue = callback(resultValue, this[i], i, this);
3}

This being said, our final solution would look like this:

JAVASCRIPT
1Array.prototype.myReduce = function (callback, initialValue) {
2  const argsLength = arguments.length;
3  //If array is empty and there is no initial value, return an error
4  if (argsLength === 1 && this.length === 0) {
5    throw new Error();
6  }
7
8  let index = argsLength === 1 ? 1 : 0;
9  let resultValue = argsLength === 1 ? this[0] : initialValue;
10
11  //Call the callback function for every element and replace the resultValue
12  for (let i = index; i < this.length; i += 1) {
13    resultValue = callback(resultValue, this[i], i, this);
14  }
15
16  return resultValue;
17};
JAVASCRIPT
OUTPUT
Results will appear here.