JavaScript Reduce… More Than Just Summing up Numbers

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:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
// expected output: 10

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.

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

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:

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
, initialValue
console.log(sum) // 6

We can use it to flatten arrays :

let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( accumulator, currentValue ) => accumulator.concat(currentValue),

Structure an object:

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

let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }

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

function groupByAge(personsArray, property) {
return const personsArray.reduce( (acc, person)=> {
let key = person[property]
if (!acc[key]) {
acc[key] = [] //if this property does not exist on accumulator
} // object, then init as empty array
acc[key].push(person) //if exist, then push the object in
return acc
}, {}) // note that accumulator is init as empty object

And then:

groupByAge(people, 'age')
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }

Try it out yourself!




Hi :)

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Reasons Why You Should Choose ReactJS For Your Next Project

How to conquer Webpack 4 and build a sweet React app

🔥To thank the Airdropfind community for its support and trust in EMIT

下载和观看 鬼灭之刃剧场版:无限列车篇 2020 (Demon Slayer: Kimetsu no Yaiba) 完整版本 HD/BluRay

Journey with React Native & NestJS [1/X]

Nuxt unit + snapshot testing

Can We Save This Beautiful Planet That Provides Us Home?

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


Hi :)

More from Medium

LeetCode 1-Two Sum | JAVASCRIPT | Study Plan-Data Structure I. Day 2

BIOS-00 Bootcamp | Onboarding at ShopUp

FizzBuzz the Interview Question Every Developer Should Know.

Onboarding guide for Junior Developers