AlgoDaily Solution

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};

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.