Using Reduce as a Counter

At some point you will need to create a counter for an algorithm. The traditional approach is to use the each function to iterate over the the collection of data and increment the count every time that value is found.

Imgur

Have you ever considered the reduce function? Reduce can be found in function libraries like underscore. It is also a native method for arrays in Javascript. However, I think most people underestimate the awesomeness of Reduce. The functionality of Reduce is to reduce the value of a collection to one value.

Imgur

A typical use of Reduce is totaling a sum of numbers in an array.

Imgur

The initial value, sometimes called memo, start, seed, or accumulator, is the starting place for the reduction. Generally, the first index is the initial value. However, have you considered starting with an array or an object?

Imgur

Using reduce, you can iterate through a collection incrementing a count that would be returned as your final result. Below I have demonstrated the awesomeness of Reduce by using it as a counter.

Imgur

Written on December 19, 2015