DEV Community

Cover image for How I understood... javascript reduce method
epresas
epresas

Posted on • Updated on

How I understood... javascript reduce method

I've been working almost for 3 years in web development, and like all learning roads, some concepts are harder to grasp than others, for me one of them was javascript reduce method.

So, I'm going to share a simple example of a real life situation that could be solved using this method.

The setup

Imagine that a coworker's birthday is coming soon, and everybody wants to pitch in to buy a present, ideally the total amount for everybody to give would be determined by a simple division: totalAmount / totalOfPeople.

But not always everyone can give the same amount (some of us live on a budget!), so a list is made with the amount each person can give, resulting in the following array:

const amountPerPerson = [
  {
    name: "Ed",
    amount: 20
  },
  {
    name: "John",
    amount: 30
  },
  {
    name: "Ari",
    amount: 15
  },
  {
    name: "Mary",
    amount: 25
  },
  {
    name: "Gonzalo",
    amount: 10
  }
]
Enter fullscreen mode Exit fullscreen mode

The solution

How would we get the total amount we have to buy the present? Enter our saviour reduce!

const totalAmount = amountPerPerson.reduce((acc, curr) => acc + curr.amount, 0);

console.log(totalAmount);
// 100
Enter fullscreen mode Exit fullscreen mode

So, what does all this gibberish do?

Ok, let's break it down... the reduce function is receiving two parameters:

A callback function, which receives two parameters also: the acc or accumulator and curr or current-value (it can also receive the index of the current element being iterated, and the array we're applying the reduce, in case you need to do something with them), reduce will iterate through each element of the array, applying the callback function to the current element and storing or "reducing" the result in the accumulator, in this example, the function adds the amount of the current person to the total.

The second parameter the reduce function gets is the starting value for the accumulator, it can be a number, an object or even another array, in this case it's 0 but imagine for our example that our good old boss (wink wink!) says something like "hey! great idea! I'll put 50 euros and you guys add the rest", our function will be something like this:

// We start with the 50 euros our great boss pitched in!
const totalAmount = amountPerPerson.reduce((acc, curr) => acc + curr.amount, 50);

console.log(totalAmount);
// 150

Enter fullscreen mode Exit fullscreen mode

I mentioned above that we could use as extra parameters of the reducer callback the index, and the array.

To stay with this example, I'm going to add a method that allows me to calculate the average per person of the amount pitched in (why would I need it? IDK, use your imagination! 😜)

const average = amountPerPerson.reduce((acc, curr, index, array) => {
    acc += curr.amount;
    if (index === array.length - 1) {
      return acc / array.length;
    } else {
      return acc;
    }
 console.log(average);
  }, 0);

// 20
Enter fullscreen mode Exit fullscreen mode

Here is a codepen to show it all in action:

And that's how I understood reduce method!

Conclusion

Although reduce array method is one of the trickiest to get at first, it can be really resourceful when trying to condense complex data into simple values for later use.

When first learning javascript, some parts might seem tricky or sometimes scary (still happens to me!), but the trick is to try and put the concept I'm trying to learn in real life situations to see if it works, and I keep my good old friend the rubber ducky nearby to explain it.

I'll be posting little bits like this, and hope this helps you on your journey to become a javascript ninja!

Thanks for reading! and feel free to comment and share.

Top comments (3)

Collapse
 
jroji profile image
Jon Rojí

Nice job! :D

Collapse
 
abayonb profile image
Alejandro Bayon

Nice explanation!

Collapse
 
drwaky profile image
Joaquín López

Great!