JavaScript reduce() method – Simple Explanation with Simple Examples
Tags: javascript, beginners, tutorial, codenewbie
Published: 2021-09-29 16:55:12

Understanding how the JavaScript `reduce()` method works is tricky. However, when properly understood, the method can be used to perform some really powerful tasks.


The `reduce()` method **reduces** an array to a single value. Technically, the method can be used to reduce an array to absolutely anything and everything. 

Reduces takes four arguments, but we will only be focusing on the two important ones. The first argument is the **accumulator**. 

The accumulator is a callback function. The reducer function essentially creates a cycle of value accumulation. In simple terms, the callback function does the following, in specified order:

-  It takes a value and returns an *accumulator value one*.
- On second iteration, It accepts that *accumulator value one* and returns *accumulator value two*.
- On third iteration, It accepts the *accumulator value two* and returns *accumulator value three*.
- This goes on until all elements in the array is iterated upon

The second argument is an **initial value**. If passed, the initial value is initialized as the accumulator. If omitted, the first item in the array will be used as the accumulator.

To demonstrate all of this, let's consider some simple, yet eye-opening examples

### How to sum up numbers with reduce()
Perhaps the most common use case is for summing up an array of numbers. I personally think this is a great example for learning how `reduce()` truly works.

```js
let numbers = [2,5,7,9]

let sum = numbers.reduce((accValue, currValue) => {
let total = accValue + currValue
return total;
})

console.log(sum); // 23
```

On the first iteration, the callback function will add accumulator value (2) with current value (5), and will return total (7). 

On the second iteration, the callback function will add accumulator value (7) with current value (7), and will return total (14). 

On third iteration, the callback function will add accumulator value (14) with current value (9), and will return total (23).

Since there is no more item in the `numbers` array, `reduce()` will return 23.

#### Passing in an initial value to reduce()

Notice something though. No initial value (second parameter) was passed into `reduce()`. In this case, the method will use the first item (2) as the accumulator value.

In the following example, we will be passing a second parameter to `reduce()`

```js
let numbers = [2,5,7,9]

let sum = numbers.reduce((accValue, currValue) => {
let total = accValue + currValue
return total;
}, 1)

console.log(sum); // 24
```
Because we set the initial value to 1, that value will be used as the default accumulator on the first iteration. So it will become 1+2 =3. Then 3+5=7 and so on.


In this case, the array simply wraps the accumulated value. Any object can also be used.

### Using reduce() to get unique values.
We can also reduce an array with duplicate content to an array with unique content.
Though you should use a `Set` collection to achieve this. I thought it was a great example to show a more different use case.

```js
let list = [
  {
    name: "Andrew",
    age: 22
  },
  {
    name: "Andrew",
    age: 22
  },
  {
    name: "Ben",
    age: 34
  },
  {
    name: "Chris",
    age: 30
  },
{
    name: "Daniel",
    age: 40
  }
];

let uniqueNames = list.reduce((uniqueNames, currentPerson) => {
  if (uniqueNames.includes(currentPerson.name)) {
    return uniqueNames;
  }
  
  return [...uniqueNames, currentPerson.name]
}, [])

console.log(uniqueNames)

// ["Andrew", "Ben", "Chris", "Daniel"]
```

We have an array called `list`. This list has duplicate content (Andrew). On each iteration, we check if the accumulator (an array) already has the `current name` inside of it. If it does, then we ignore the current name and just return the accumulator the way we received it. This will help us avoid adding a duplicate.

If the current name doesn’t exist in the accumulator, then we will add that name into the accumulator (using spread) and return the accumulator.

In the end, the accumulator (uniqueNames) will have only unique names, and no duplicates. 

Notice that we had set our initial value or an array literal `[]`. In this case, the accumulator is passed into the array.

So in the end, we transform an array which contains duplicate content to **another** array which has unique content.


### Wrapping up
`reduce()` usually can feels difficult to understand, though it doesn't have to be. The method gets even more powerful when used to reduce arrays to other data types, like objects.

To summarize, the method performs a consistent accumulative action on every item within an array. 

Make sure to join my  [newsletter](https://www.getrevue.co/profile/ubahthebuilder) 

Thanks for reading.


> 
P/S: If you are learning JavaScript, I created an eBook which teaches 50 topics in JavaScript with hand-drawn digital notes. Check it out  [here](gum.co/js-50) .