How to use the `reduce` Method in JavaScript (and React)
Tags: javascript, es5, reduce
Published: 2019-11-20 10:20:27

---
title: How to use the `reduce` Method in JavaScript (and React)
published: true
description: Learn about what the reduce method is with two examples (a simple example and another for use in React)
tags: JavaScript, ES5, reduce
---

# What is `reduce`
It's an ES5 method in JavaScript like `for..each` and `map` which we can use with arrays.

The difference is:
- as the name suggests it reduces the number of values in an array to one. 
- we have access to the array's previous value apart from its current value and index.
- we will send the accumulator's start value to the callback function; so when we first start previous value will be the same as the accumulator's start value

# A Simple Example of Using `reduce` 
Let's look at a simple example that uses `reduce` to count the total of an array.
Imagine you have an array: `[98,45,33,47,100,80]`
We can write the following code to use the `reduce` method to sum up the values in this array: 
```javascript
const scores = [98,45,33,47,100,80];
const totalScores = scores.reduce(
(previousScore, currentScore, index)=>previousScore+currentScore, 
0);
console.log(totalScores); //returns 403
``` 
What happens in the code is:
1. we call the `reduce` method on the array `scores`.
2. the method has access to the array's `previous` value, `current` value and `index`. 
*We don't use `index` in this example.
3. we send zero as the `accumulator`'s initial value. 
4. in our example when the method first runs (where `currentScore` is 98), `previousScore` assumes the value of zero as sent to the callback function.
5. the result of `totalScores` is 403.
5. if we change the initial value of the `accumulator` to 100, the value of `totalScores` then changes to 503.

```javascript
const scores = [98,45,33,47,100,80];
const totalScores = scores.reduce(
(previousScore, currentScore, index)=>previousScore+currentScore, 
100);
console.log(totalScores); //returns 503
``` 

# Using `reduce` in React
Imagine you have the following data structure in the `App` component:
```javascript
  const course = {
    name: 'Half Stack application development',
    parts: [
      {
        name: 'Fundamentals of React',
        exercises: 10,
        id: 1
      },
      {
        name: 'Using props to pass data',
        exercises: 7,
        id: 2
      },
      {
        name: 'State of a component',
        exercises: 14,
        id: 3
      }
    ]
  }
```
To display the total number of exercises in in the `Total` component:
1. from `App` send `parts` as a prop to `Total`:
2. in `Total`, call the `reduce` method on `parts`.
3. `parts` contains multiple values `name`, `exercises` and `id`.
4. so we explicitly specify `exercises` as the value we want to use in the calculation.

- `App.js`:

```javascript
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Total from "./components/Total";

const App = () => {
  const course = {
    name: "Half Stack application development",
    parts: [
      {
        name: "Fundamentals of React",
        exercises: 10,
        id: 1
      },
      {
        name: "Using props to pass data",
        exercises: 7,
        id: 2
      },
      {
        name: "State of a component",
        exercises: 14,
        id: 3
      }
    ]
  };

  return (
    <div>
      <Total parts={course.parts} />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
```
- `Total.js`:

```javascript
import React from "react";

const Total = props => {
  const total = props.parts.reduce(
    (prevValue, currentValue) => prevValue + currentValue.exercises,
    0
  );
  return <p>Totalzzz: {total}</p>;
};

export default Total;
```
- Result:
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/2407xvxejocp7jeju2qm.jpeg)

Hope this helps!