Typescript 101 – the reduce() method

Typescript 101 - the reduce() method

This is the fifth post of a blog series where each post will touch a popular TypeScript method, function or feature with example. If you’re starting with TypeScript (or JavaScript) you might not be familiar with all of these powerful tools that can shorten your codebase and help you in day to day development

This post we will discuss the .reduce() method.

.reduce()

Let’s say an API call like:

const result = await service.retrieveDrinkers.promise();

Returns a list of beer loving engineers which looks like this:

const drinkers = [
    {
        name: 'marcel',
        beers: 5
    },
    {
        username: 'roger',
        beers: 8
    },
    {
        username: 'jan',
        beers: 6
    },
    {
        username: 'dirk',
        beers: 4,
        sparood: 2
    }
];

If we would like to get the total of beers for all of them then with .reduce(), it’s pretty simple:

const totalBeers = drinkers.reduce((count, person) => count + person.beers, 0);

We have to instantiate the value of count which we do with the 0 (zero).

Another handy feature to use reduce() is that you can use it to get the highest value in an array as well. Let’s say we want to find the person with the most beers:

const max = drinkers.reduce((prev, current) => (prev.beers > current.beers) ? prev : current)
console.log(JSON.stringify(max));

will return:

{"username":"roger","beers":8}

Summary

So how does it work ? The .reduce() function runs a callback for each element of the array. Where the very handy side-effect is that it passes the result of this callback (count) from one array element to the next.

Make sure to also check our other TypeScript 101 posts.

Hope it helps!