Reduce
Sometimes you don’t need to transform each item of a collection the way that map or for does. Sometimes what you need is to combine all the elements of a collection into a single value. For this we have reduce. Like map, reduce takes a function and a sequence and calls the function for each item in the sequence. Unlike map, reduce passes two arguments to the function—along with the element from the collection, your function gets called with the current result. Each time reduce calls your function, it updates the current result with the return value from that call. When reduce runs out of elements, it returns the last result.
Although there are a lot of variations on how you can use reduce, the easiest to grasp is where you pass in three ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access