Time for action — writing the reduce function to process emitted information

This could be the reduce function for the previous example:

function(key, values) {
var result = {votes: 0}
values.forEach(function(value) {
result.votes += value.votes;
});
return result;
}

What just happened?

reduce takes an array of values so — it is important to process an array every time. Later on in the book we shall see how there are various options to Map/Reduce that help us process data.

Let's analyze this function in more detail:

function(key, values) {
var result = {votes: 0}

values.forEach(function(value) {
result.votes += value.votes;
});
return result;
}

The variable result has a structure similar to what was emitted from the map function. This is important, as we want the results from every document in the same format. If we need to process more results, we can use the finalize function (more on that later). The result function has the following structure:

function(key, values) {
var result = {votes: 0}
values.forEach(function(value) {
result.votes += value.votes;
});

return result;
}

The values are always passed as arrays. It's important that we iterate the array, as there could be multiple values emitted from different map functions with the same key. So, we processed the array to ensure that we don't overwrite the results and collate them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.59.37