One Pager Cheat Sheet
Using the built-in JavaScript method
reduce()you can create a single value from the elements in an array by running a user-supplied "reducer" callback function on each element, optionally passing an initial value first.
- We created a custom function,
myReduce
, that takes a callback function and an optionalinitialValue
as arguments, and loops through the array elements by calling the callback with the adequate parameters, returning the final result value.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
17
Array.prototype.myReduce = function (callback, initialValue) {
const argsLength = arguments.length;
//If array is empty and there is no initial value, return an error
if (argsLength === 1 && this.length === 0) {
throw new Error();
}
let index = argsLength === 1 ? 1 : 0;
let resultValue = argsLength === 1 ? this[0] : initialValue;
//Call the callback function for every element and replace the resultValue
for (let i = index; i < this.length; i += 1) {
resultValue = callback(resultValue, this[i], i, this);
}
return resultValue;
};
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
You're doing a wonderful job. Keep going!
If you had any problems with this tutorial, check out the main forum thread here.