11/13/2017 - 2:44 PM

ES5 - Array.prototype.reduce()

The .reduce() function is one which I found difficult to wrap my head around, so I'm going to try and break it down. Unlike the .map() function, .reduce can be used to return not just an array, but also an object, number, string or whatever else you'd like. Some of the use cases of the reduce function are flattening, ordering and adding/subtracting/calculating.

// Reduce takes in two arguments, a function and an optional starting point. 
// example 1
[1, 2, 3].reduce((prev, curr, index) => {
    console.log(prev, curr, index);
    return prev + curr;

// An example of a function that takes in any list of numbers as arguments
// and returns the total sum through a reduce function
function addNumbers() {
    return Array.from(arguments).reduce((a, b) => a + b);

const total = addNumbers(55, 399, 392, 18, 44, 98, 76, 29);