
Javascript Array Helper: reduce()
The reduce array helper is probably the most difficult of the array helpers to explain and understand.
The purpose of the reduce() array helper is to execute a function for every array element and reduce the entire array to a single value.
A Practical Example
Suppose we have an array of numbers and we want to find the sum of all elements.
First, let’s look at how we would do this in older ES5 javascript.
var numbers = [ 10, 20, 30]; var sum = 0; for (var i=0; i<numbers.length; i++) { sum += numbers[i]; } console.log(sum);
Javascript reduce() Helper
Here is how the example above would be re-written using the reduce helper.
var numbers = [ 10, 20, 30]; var sum = 0; sum = numbers.reduce(function(sum, number) { return sum + number; }, 0); console.log(sum);
So this helper is a little different from the rest because in the callback function, there are two parameters. The first is an accumulator value and the second is the normal current element being processed. Also, after the function callback there is another parameter to set the initial value for the first iteration.
The signature looks like this.
var result = array.reduce(callback, initial value)
or more specifically
var result = array.reduce(function(accumulator, current element), initial value)
So for our example of summing the elements of an array, the way this reduce would work is that for each array element, a callback function will get called and the accumulator will get incremented by the current element value. If it is the first iteration then the accumulator will start at the initial value.
The end result is one single value returned. In our example the final sum of everything in the array.
Hope this helps, in my next post I will discuss if the array .every and .some functions.