For a basic example of using reduce, it would be good to start with just an array of numbers. Often there ends up being a situation it which something needs to be done that involves summation, such as when figuring out an arithmetic mean for example. Although other more specific methods like _.sum, and native loops can be used, this is a post on reduce so…
With the lodash _.reduce method I just give the array of numbers as the first argument, and then a iteratee method as the second argument. In this method the first argument is the accumulator, the second is the current key or index value, the third argument is the key or index, and then the fourth argument is the collection (array or object).
This works fine because the first element in the collection is a number, so then the starting value of acc is a number, and then all additional values are numbers as well, so I do not have to do anything fancy with type detection, or recursive processing with this example. In other words the function is only called three times, and on the first call the value of acc is the value of the first element in the array, so I can just add.
So if I am only working with arrays then there is not much need for _.reduce, because in most cases the Array prototype equivalent of this will work just fine.
However this is just a simple example that involves working with an array, and not an object in general, or an array like object such as an instance of HTMLCollection.
In most cases an array like object will have a length propety just like with an Object created with the Array constructor, but with _.reduce in lodash it does not even have to have that.
Also the object does not have to have key values that are consistent with index numbers as well. The _.reduce method will find all that out for me behind the senses, and I do not have to spend time writing, or hunting down a vanilla js solution for thouse kinds of situations as well.
3.2 - The same can be done with Array.reduce, but I need to use call, and the object must have a length property.
So call (also apply, and bind) come in handy when trying to make a prototype method work with another object that does not have that method in it’s prototype. So this does allow for me to get Array.reduce to work, assuming the object does have a length property, and the key values are constant with what would be an Array.