DEV Community

Alexa Gamil
Alexa Gamil

Posted on • Updated on

Reduce() Method in Javascript

The reduce() method was one of the array methods that intrigued me when I was a complete noob learning Javascript. After looking over it's syntax and terminology, I ran as far away as possible and never looked back! (haha!)

I was too focused on trying not to forget my semi-colons (;) at the time so I said, I’ll get back to that when it looks less bewildering.

So here I am writing my very first blog about this actually amazing method!

Description

The reduce() method reduces an array to a single output.

To add more context, a reducer function is executed on each element of the array, then returns a single output value after it iterates on the very last element. And by single output value, it could be an integer, an array, or an object.

You can think of it as reduception, You have a reduce method and inside that method you have a reducer method. (What?!)

I think breaking down the syntax makes this easier to understand!

Syntax

array.reduce(callback( accumulator, currentValue, index, array ) {
  // return accumulator result from executing something
},[initialValue]);
Enter fullscreen mode Exit fullscreen mode

Parameters

  1. Callback is the reducer. It is the function that is executed to each element of the array.

When you think about it, it is “calling back” or “looping back” the function for each element of the array.

Callback takes four arguments: accumulator, currentValue, index, array.

a. Accumulator is the running total that accumulates the callback’s return values.

b. CurrentValue is the current element the callback is executing on.

c. Index is the current element’s index the callback is executing on (optional)

d. Array is the array that the method was called on. (optional)

The Index and Array arguments are optional. The reduce method will still work without them. We will look at an example later where we will need them.

  1. initialValue (if provided) is the value passed as the initial accumulator to the first callback. This is optional depending on what output you’re trying to achieve. If you’re just trying to combine numbers together and you don’t provide an initial value, the very first index of the array becomes the default value of the accumulator and the first callback will be executed on the second index of the array.

Now that we all got the boring(but important!) stuff down, let’s get to it!

Example 1 - Getting the sum of integers in an array

Normally to get the sum of the integers in an array you would use a for loop.

let array = [5, 10, 15, 20]; 
let total = 0

for(let i = 0; i < array.length; i++){total += array[i]}
total // 50
Enter fullscreen mode Exit fullscreen mode

Using reduce() to get the same answer.

const array = [5, 10, 15, 20]; 
const sum = array.reduce(function(acc, cv){return acc + cv})
sum // 50
Enter fullscreen mode Exit fullscreen mode

Using reduce we didn’t need to define a variable outside the scope, the reduce method have an accumulator(acc) that remembers the return value for each callback.

Since our main goal is to just add numbers, we didn’t need to provide an initial value. When not provided the accumulator’s(acc) initial value is set to the first element of the array which is 5.

The first callback(function) will be executed on the second element, so the currentValue is 10.

In this function our callback is to add the currentValue to the accumulator. This will happen for every single element. Once it’s done executing the callback for each element, the method will return the final accumulator value.

Makes sense right? (...no? Ok keep reading!)

Example - 2 Reducing an array of objects

You can also use reduce() on an array of objects and get one object in the end!

Let’s say you decided to start keeping track of your diet.
(I made up an inaccurate table representing each meal, so don’t judge me)

const meals = [
  {meal: 'breakfast', carbs: 90, fat: 200, calories: 600,},
  {meal: 'lunch', carbs: 70, fat: 100, calories: 400},
  {meal: 'salad', carbs: 100, fat: 80, calories: 800,}
];
Enter fullscreen mode Exit fullscreen mode

We will use reduce() to output an object that will have the total daily intake for each category (carbs, fat, and calories).

const intake = meals.reduce(
  ({ carbs, fat, calories }, meal) => ({
    carbs: carbs + meal.carbs,
    fat: fat + meal.fat,
    calories: calories + meal.calories,
  }),
  {carbs: 0, fat: 0, calories: 0}
)
intake // { carbs: 260, fat: 380, calories: 1800 }
Enter fullscreen mode Exit fullscreen mode

Since we wanted a specific output we declared an Object as the initial value of total(accumulator). We also provided categories as keys pointing to a value of 0. For each callback, we grab the value of .carbs, .fat, and .calories and add it to the appropriate property. In the end you should have one Object that has the total for each category.

Still reading?...Hang in there, I have one more!

Example 3 - Getting the average

let grades = [90, 85, 94, 87];
Enter fullscreen mode Exit fullscreen mode

We can also use reduce() on this array to get the average

let average = grades.reduce((total, grade, index, array) => {
 return total += grade/array.length
}, 0);
 average // 89
Enter fullscreen mode Exit fullscreen mode

If you notice, we added the index and the array as arguments. Having access to the original array this method is called on, allows us to divide the accumulator's total by array's length and get the average. Even though we didn't use the index here, we had to provide it. If we didn't provide the index and only passed the array, our method will think that we are calling index.length instead of array.length

Conclusion

Besides the examples I provided, you can also use reduce to create a tally, flatten arrays, replacement of map() method, and so many more! What I like about it is being able to write different functions inside the callback and repeat the same logic for each element of the array.

I am no expert on the reduce() method, every day I am still learning of various ways to use it.

As a beginner in coding I am writing about it to inform other beginners like me that although it may look intimidating, learning it could only be to your advantage. The reduce() method is powerful.

Oldest comments (5)

Collapse
 
primelos profile image
carlos fabian venegas

Great Examples!

Collapse
 
gamil91 profile image
Alexa Gamil

Thank you!!!

Collapse
 
lexlohr profile image
Alex Lohr

Using modern syntax (arrow function, object decomposition) makes your example simpler and more readable:

const intake = meals.reduce(
  ({ carbs, fat, calories }, meal) => ({
    carbs: carbs + meal.carbs,
    fat: fat + meal.fat,
    calories: calories + meal.calories,
  }),
  {carbs: 0, fat: 0, calories: 0}
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gamil91 profile image
Alexa Gamil

This is awesome! Thank you for this. Would it be ok if I update my blog and use that?

Collapse
 
lexlohr profile image
Alex Lohr

Please do. You're welcome.