Array.prototype.reduce
Easy
·
45 minutes
Prompt
reduce
is a function that can be called on JavaScript arrays: it is passed a callback function and an initial value for the 'accumulator' value. The callback is called against each element in the array, along with the accumulator value, and the accumulator is updated to the return value of the callback. This allows you to take an array of values and reduce it down to a single value. For example:
const myArray = [1, 2, 3, 4, 5];
const arrayTotal = myArray.reduce((accumulator, currentElement) => accumulator + currentElement, 0);
// The iteration through myArray will look like so:
// Index 0: accumulator=0 (initial value) currentElement=1
// accumulator updated to accumulator+currentElement = 0 + 1 = 1
//
// Index 1: accumulator=1 currentElement=2
// accumulator updated to accumulator+currentElement = 1 + 2 = 3
//
// Index 2: accumulator=3 currentElement=3
// accumulator updated to accumulator+currentElement = 3 + 3 = 6
//
// Index 3: accumulator=6 currentElement=4
// accumulator updated to accumulator+currentElement = 6 + 4 = 10
//
// Index 4: accumulator=10 currentElement=5
// accumulator updated to accumulator+currentElement = 10 + 5 = 15
You should implement your own version of reduce, which can be passed an array, an initial value, and a callback, and will return the final value of the accumulator. For example:
function reduce(array, callback, initialValue) {
// add your code here
}
const factorial = reduce([1, 2, 3, 4, 5], (accumulator, currentElement) => accumulator * currentElement, 1);
console.log(factorial);
// 120
Submitting solutions
- Create a solution by forking one of our CodePen templates:
- Submit your solution here