Array.reduce and its Parameters and reduceRight.
One last useful feature of Array.reduce() are its optional parameters. Let's go through them. There are some occasions when it's useful or necessary to know the index we are on, or you'll need the array itself.
- A reducer function (required)
- The Current value (optional). If you don't pass one in, the first value of our array becomes our initial value.
- The Current index
- The Array we are iterating over.
Here's another arbitrary example of using the index and array. Imagine you're iterating over a large dataset but you only need to iterate over half of the data. You can do so by using the Array (4th) parameter length method and dividing it by half. When it reaches that index, have it return out of the reducer.
There are many uses cases for Array.reduce, the point I'm trying to make is Array.reduce can be pretty useful for some complex logic. In my opinion, make use of built-in methods first, and if you find yourself chaining method after method, consider using a reducer.
Another interesting Array method is Array.reduceRight()
. Maybe you're iterating over a new user
object and you'd like to see the reduce an array to it's newest users first. We can use Array.reduceRight and it will start at the end of the array, and work it's way in descending order.
I hope these articles have been helpful and stripped away some of the magic of Array.reduce.
Thanks for making it this far.
Ariel