Using a while-loop – Example # 1
See the Pen Array.prototype.reduce() – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.
When I said that this approach “…has worked for us”, you may notice that I didn’t say that it “…worked well”. This is because the approach we took solved a problem, but created a couple of issues, the main one being boilerplate code. Most of the code in our “while” loop will be repeated if / when we need to solve the same problem elsewhere in our code. In addition to that, we have created an “i” variable to keep track of our counting during our “while” loop. It may seem innocent, but the more variables we create, the more variables we need to manage. Fewer variables is better.
See the Pen Array.prototype.reduce() – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.
The Array reduce() method has dramatically simplified things in Example # 2. Notice how, in the getTotal the variable is now an anonymous function. In this function, we add the accumulator and currentValue arguments. Now you may be wondering: “What are the accumulator and currentValue arguments?” Well, take a look at the last line of code: milesPerDay.reduce(getTotal). What’s happening here is, we’re executing the .reduce() method of our “milesPerDay“, passing it the getTotal as an argument. This is the anonymous function that we detailed a few sentences ago.
So, the reduce method iterates the array and provides access to not only the currently iterated value (i.e. the current array element), but also the value that was returned by the previous execution of this function. This allows you to “accumulate” values across the array.
Example # 3
See the Pen Array.prototype.reduce() – Solution – 2 by Kevin Chisholm (@kevinchisholm) on CodePen.
Example # 3 does not provide any additional value with respect to solving the problem; the solution from Example # 2 is solid. The purpose of Example # 3 is to offer more detail about the arguments that are passed to the function provided to the Array reduce() method.
As demonstrated in the UI, the first argument is the accumulated value that’s being created as you iterate the array (i.e. the value returned by the last execution of this same function). The second argument, “currentValue”, is the value of the current array element. In the third, the index of the current array element is provided, and in the last, we see the array over which you are iterating.
I decided to show the value of the “array” argument to demonstrate that the Array reduce() method does not itself make any changes to the original. You can do that within the function passed to the Array reduce() method, but reduce() itself does not make any such changes. What you choose to do with these arguments is up to you, but just know that they’re helpful in building the logic you need to reduce your array to one final value.