There is a pattern here that is useful. If you squint your eyes you'll see that we have an array with a single data type (Number) and we have binary operation that works with that data type (add).
That simple pattern can be applied to more complex data types. Let's make an example with nested arrays.
In here we create a new array with the unique elements of each array.
Notice how in the functions add and intersection don't mention anything about an accumulator or a currentValue? That's the power of reduce. I guess you can say that it can "increase the capacity" of a binary operation. This in my opinion is the best use of reduce.
Now, don't take these example to the letter, I'm not trying to say these exact situations are a good use of reduce. I'm trying to show a pattern where reduce can shine.
I can talk about the "good use case" a little bit.
Let's start with the classic, adding numbers.
There is a pattern here that is useful. If you squint your eyes you'll see that we have an array with a single data type (Number) and we have binary operation that works with that data type (add).
That simple pattern can be applied to more complex data types. Let's make an example with nested arrays.
In here we create a new array with the unique elements of each array.
Notice how in the functions
add
andintersection
don't mention anything about anaccumulator
or acurrentValue
? That's the power ofreduce
. I guess you can say that it can "increase the capacity" of a binary operation. This in my opinion is the best use ofreduce
.Now, don't take these example to the letter, I'm not trying to say these exact situations are a good use of
reduce
. I'm trying to show a pattern wherereduce
can shine.I talk about this in more detail in this article.