5 Minute JavaScript #18: reduce

The past weeks we dived in the wonderful world of array methods. Previously we already discussed forEach, filter, some and every, and map. Today we’ll take a look at the reduce method. While being extremely useful, its concept can be hard to grasp.

Also known as fold (in this case foldLeft) in other functional programming languages, reduce kan be used to combine all elements of an array into one single return value. That return value can be anything. It could be an array (then the reduce functions as a filter/map), but it can also be: an object, string, number, boolean… Everything is possible.

A simple example can be to use the reduce method for calculating a sum. Here’s the code how we would write it in any other imperative language.

var numbers = [1, 2, 3];
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
	sum += numbers[i];
}

We can rewrite this code as follows using the reduce method

var sum = numbers.reduce(function (prev, cur) { return prev + cur; });

The reduce callback function takes two important parameters (prev, cur in this case). First of all we have the previous value. This is the value that got returned in the previous callback function. The current parameter is the current item in the list.

You might get your head around this functionality, but it’s not really useful in real applications. Its real strength lies in the fact that you can press a lot of elements together into one single return value. A use case for reduce might be this:

var user = { id: 'UUID', version: 0 };
var users = [/* list of users */];
var idVersionMap = users.reduce(function (map, user){ 
    map[user.id] = user.version; 
    return map; 
}, {});

In our blogpost about the map method we used map to create a new list of objects (with id and version). Here, we use the reduce method to create a single object that acts as a map with key = id and value = version. The empty {} that we passed along in the reduce callback function is the initial value the method needs to use.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

About Arvraepe