Ultimate guide to master JavaScript's reduce functions
Tags: javascript, beginners, programming, tutorial
Published: 2023-02-01 13:13:28

The reduce function in JavaScript is a powerful tool for transforming an array of values into a single value. It is a higher-order function, which means that it takes one or more functions as arguments and returns a new function. In this article, we will cover the basics of how to use the reduce function and provide some examples to help you get started.

## What is the reduce function and how does it work?

The reduce function is a method that can be called on an array object in JavaScript. It takes two arguments: a callback function and an optional initial value. The callback function is called on each element in the array, starting with the first element and continuing until all elements have been processed. The result of each call to the callback function is used as the input to the next call, and the final result of the last call is returned by the reduce function.

The initial value is an optional argument that can be used to set the starting value for the first call to the callback function. If an initial value is not provided, the first call to the callback function will be made with the first two elements in the array.

## Cool right? Now let's see how to actually use it:

To use the reduce function, you must provide a callback function that takes two arguments: the accumulator and the current value. The accumulator is the result of the previous call to the callback function and the current value is the value of the current element in the array. The callback function should return a new value that will be used as the accumulator in the next call to the callback function.

Here is a simple example of how to use the reduce function to sum the elements in an array:


```js
const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((acc, curr) => acc + curr, 0);

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

In this example, the initial value is set to 0 and the callback function adds the current value to the accumulator. The result of each call to the callback function is used as the input to the next call, and the final result of the last call is returned by the reduce function.

More examples of the reduce function:

### Finding the maximum value in an array:  

```js
const numbers = [1, 2, 3, 4, 5];

const max = numbers.reduce((acc, curr) => acc > curr ? acc : curr);

console.log(max); // 5
```

### Counting the frequency of elements in an array:  

```js
const words = ['apple', 'banana', 'apple', 'cherry'];

const frequency = words.reduce((acc, curr) => {
  acc[curr] = (acc[curr] || 0) + 1;
  return acc;
}, {});

console.log(frequency); // { apple: 2, banana: 1, cherry: 1 }
```

### Flattening an array of arrays:  

```js
const arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flattened = arrays.reduce((acc, curr) => acc.concat(curr), []);

console.log(flattened); // [1, 2, 3, 4, 5, 6, 7, 8, 9
```

### Transforming an array of objects into a hashmap:  

```js
const users = [{ id: 143, name: 'Matheus' }, { id: 150, name: 'Lucas' }, { id: 181, name: 'Victor' }]

const usersHashMap = users.reduce((users, currentUser) => {
  const { id, ...rest } = currentUser;

  users[id] = rest

  return users
}, {})

console.log(usersHashMap)

/* {
    "143": {
        "name": "Matheus"
    },
    "150": {
        "name": "Lucas"
    },
    "181": {
        "name": "Victor"
    }
} */
```


### BONUS: Typescript example of a dynamically created object with type inference from the input to the output

```js
const usersRouter = {
    "getUser": "/users/get"
}

const createApi = <T extends {[key: string]: string}>(router: T) => {
    return Object.entries(router).reduce((api, [method, endpoint]: [keyof T, string]) => {
        api[method] = () => fetch(endpoint)

        return api
    }, {} as Record<keyof T, () => Promise<any>>)
}

const usersApi = createApi(usersRouter)

const result = usersApi.getUser() // You get autocomplete on the dynamic API methods


```

## Final considerations

The reduce function is a powerful weapon that we can use to transform data with more freedom. With it, we can achieve the same results as map or filter but with more control to solve a lot of other problems. A reminder that reduce is a higher-order function, not exclusive to the JavaScript language. Let me know if you have any questions!