JavaScript Reduce… More Than Just Summing up Numbers

Image for post
Image for post
Photo by Payoon Gerinto on Unsplash

For a lot of people, the first time when we know about .reduce function in JavaScript is probably when we use it to sum up an array of numbers, like:

But there’s actually a lot more to that. For example, for who starts to use Redux, you may learn about the reducer function originates from .reduce and even have had a look at the source code.

Back to the basics, essentially the reduce() method executes a reducer function on each element of the array, resulting in single output value.

The reducer function takes four arguments:

  1. Accumulator (acc)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (src)

It optionally takes an initial value as well.

So what are the use cases with advanced .reduce function?

Starting from the last example to count numbers, we can count an array of objects:

We can use it to flatten arrays :

Structure an object:

For example, we want to group a list of objects by one of their common properties:

Now in order to group the people by age, we pass the objects into reducer.

And then:

Try it out yourself!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store