Map Reduce Illustrated

Map and Reduce are 2 very useful methods available in Javascript Arrays, Ruby Enumerable and Java Stream. With these 2 methods, arrays can be transformed and manipulated in many different ways to achieve a desired outcome.

The methods themselves are known by various names in different languages.

Language Map Reduce
Javascript Array.prototype.map() Array.prototype.reduce()
Ruby Enumerable#map
Enumerable#collect
Enumerable#reduce
Enumerable#inject
Java Stream.map() Stream.reduce()

These methods take in a function that will be applied to individual elements of the array, enumerable or stream (or list, for simplicity sake). They'd return a new object with the resulting transformation without mutating the original object.

Map

Map is rather straight forward. It creates a new list by transforming each element of the original list using the given function.

In this illustration, the list is transformed using a function that multiples its input by 2.

Map illustration

Reduce

Reduce works slightly differently. Instead of going through the elements of a list one by one, it picks 2 consecutive elements and combines them into a new element using the given function. Reduce iterates through the elements of the list until it reaches the end and it returns a single final result.

In this example, a list is reduced using a function that sums 2 elements. The result is the sum of all the elements of the original list.

Reduce illustration

Reduce also accepts another parameter which would act as the starting value prior to applying the function to the elements.

Reduce with initial value

Albert Salim

Software developer at ThoughtWorks, part time triathlete, occasional photographer.

Subscribe to Albert Salim

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!