Quick guide to Javascript reduce function

1
150
Quick guide to Javascript reduce function

Introduced in ECMAScript 5.1, Javascript reduce function has proved that it is indeed a really power function to use.

If you’re new to Javascript, you might’ve heard of this reduce() function and feel it awkward to understand or to use.

Okay, in this article, I will guide you through several usages of this function.

Table of Contents

Javascript reduce function

First of all, let’s talk about the definition. Here how it looks.

arrayObject.reduce( function (accumulator, currentValue, currentIndex, array) {
    // do something here
}, initialValue);

By definition, reduce is a process that tries to apply a callback function for each array element to produce a single value.

The callback function will provide 4 arguments for developers to handle each array element iteration.

  • accumulator: the result value of previous iteration will be passed on the next iteration through this argument. For the first invocation, its value is from initialValue.
  • currentValue: the current element of the array to be processed.
  • currentIndex: (optional) the index of element in array.
  • array: (optional) the original array that being reduced.

Sound a little bit complicated, right?

Don’t worry! The purpose of this article is to help use understand it.

To see how it works, I will show you some examples to get the concept.

Calculate sum of arrays

Beside using a for loop to calculate sum of an array, you can use reduce function. It was created for this task and pretty good at it.

Look at following demonstration.

var coll = [1, 2, 3];

var sum = coll.reduce( function (total, current) {
    return total + current;
}, 0);

It might not make sense at first look. So please checkout below table for value change in each iteration of function call.

Iteration total current sum = total + current ( = total )
1 0 ( = initialValue ) 1 1
2 1 2 3
3 3 3 6

At first iteration, total value is initialValue, and current is the first value of array.

After calculation, the first result of callback function will be passed as total value of the next iteration.

And so on to the end.

Does it make sense to you right now?

If not, please read above table again and try to map value to each variable, you should write it down step by step to see how values change during each invocation.

Alright, let’s move to another example of reduce.

Flatten arrays

It is not necessary to use reduce to produce a single value, it can be an array or an object, too.

For example, with this nested array [ [1, 2], [10, 20], [100, 200] ].

What would you do to flatten it?

Using for loop would be really complicated, but with reduce , everything gets simpler.

var coll = [ [1, 2], [10, 20], [100, 200] ];

var flatArray = coll.reduce( function (flatten, current) {
    return flatten.concat(current);
}, []);

Similar to what I explained in previous section, this example show you the way to reduce a nested array into a flat array.

concat() is indeed a pretty nice function to merge two arrays into a new array. So we don’t have to loop through each array element and add to new array. This is so plainly naive way to combine arrays!

Pair nicely with ES6 fat arrow

Fat arrow is a pretty nice feature in ECMAScript 2015, and it works nicely with reduce to improve readability.

So we can re-write the above example like this.

// formal
var sum = coll.reduce( function (total, current) { return total + current; }, 0);

// with fat arrow
var sum = coll.reduce( (total, current) => total + current, 0);

If you’re a fan of Javascript one-liner, you might already know it.

Pipe functions

Pipeline is a design pattern that allows to execute functions like a chain. We can use reduce  to create a pipe for that.

Following is a simple pipe for two functions.

var pipe = (f, g) => x => g(f(x));

var double = x =>; 2 * x;
var triple = x => 3 * x;

var comboDT = pipe(double, triple);

comboDT(2); // result: 12

What if we want to create a pipe of several functions as arguments, instead of having just two functions; how would we create that pipe function?

reduce function comes to the rescue.

var pipe = (...fns) => x => [...fns].reduce( (acc, fn) => fn(acc), x );

var double = x => 2 * x;
var square = x => x * x;
var triple = x => 3 * x;

var comboDT = pipe(double, triple);
var comboDST = pipe(double, square, triple);
var comboSST = pipe(square, square, triple);

comboDT(2);    // result: 12
comboDST(2);   // result: 48
comboSST(2);   // result: 48

Wow, it looks pretty neat and clean apparently.

Also, it’s worth to mention the usage of the rest spread syntax of ECMAScript 2015.

Conclusion

By the look of it, the Javascript reduce function looks a little complicated.

However, if you know how it works and what it is capable of, you will feel the like of it. I was several years ago, but now, I do really use reduce function often in my code.

At this point, if you still feel it is hard to understand Javascript reduce array function, I really recommend to read this post again, try to type the example with your own code. You will get to know it in no time. Guaranteed!

Finally, if you like this tutorial, please subscribe or follow us on FacebookTwitterGoogle+ and Youtube to get updates on latest programming tutorials.