It's actually the JavaScript array reduce function rather than being something specific to TypeScript. As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. Reduce function does not reduce anything.

Understanding the Context

Reduce is the function to take all the elements of an array and come out with a single value out of an array. All of the above answers have explained the arr.reduce() for addition only, what if I want to perform something else with the reduce, like subtraction, multiplication etc. 57 I have this code for a class where I'm supposed to use the reduce() method to find the min and max values in an array. However, we are required to use only a single call to reduce.

Key Insights

The return array should be of size 2, but I know that the reduce() method always returns an array of size 1. 0 Reduce functional version with break can be implemented as 'transform', ex. in underscore. I tried to implement it with a config flag to stop it so that the implementation reduce doesn't have to change the data structure that you are currently using. ...

Final Thoughts

Usage1, simple one ... Usage2, use config as internal variable ... Usage3, capture config ... Keep in mind that using filter and then reduce introduces additional full iteration over array records. Using only reduce with else branch, like in the other answers, avoids this problem. Source Both map and reduce have as input the array and a function you define.

They are in some way complementary: map cannot return one single element for an array of multiple elements, while reduce will always return the accumulator you eventually changed. map Using map you iterate the elements, and for each element you return an element you want. For example, if you have an array of numbers ...