1. Code
  2. Coding Fundamentals

5 Real-Life Uses for the JavaScript reduce() Method

Scroll to top
7 min read
40

In this article, we'll take a look at some handy uses for the JavaScript array reduce method. I'll show you five practical uses, including finding the sum of an array.

What Is the reduce() Method?

The JavaScript array reduce method is a built-in iteration method used for performing an accumulative action on an array:

1
array.reduce(callback, initialvalue)

The method accepts a callback function that's called once for every item in the array. Every callback function call must always return an accumulated value.

The second argument passed to reduce() is an optional initial value which is used as the accumulator on the first iteration. If the second argument is omitted, the first item in the array will be used as the initial value instead.

The JavaScript reduce() method is very versatile, with some really handy use cases, even though it is widely considered to be the most confusing of all JavaScript iterators.

Let's take a look at some use cases for the JavaScript reduce() method.

1. Summing an Array Using reduce()

The easiest and perhaps most popular use of the JavaScript reduce method is to get the sum total of a list of numbers.

For example, here's the code for summing together the total points using reduce:

1
const topSix = [
2
    { name: "Nigeria", position: "1st", points: 43 },
3
    { name: "England", position: "2nd", points: 37 },
4
    { name: "USA", position: "3rd", points: 35 },
5
    { name: "South Africa", position: "4th", points: 30 },
6
    { name: "Brazil", position: "5th", points: 27 },
7
    { name: "Korea", position: "6th", points: 23 }
8
]
9
10
const totalPoints = topSix.reduce((acc, currTeam) => acc + currTeam.points, 0);
11
12
console.log(totalPoints) // Prints 195

On every iteration, we simply added the current teams' points to the previously accumulated points, and then we returned that as the accumulated value for the next iteration.

Another very similar use for JavaScript reduce() is to get the total count of items within an array collection, like getting the team count:

1
const teamsCount = topSix.reduce((acc, currTeam) => acc + 1, 0);
2
3
console.log(teamsCount) // Prints 6

Of course, it's better to use the count property to get the total count of an array, but this example shows how you can count using reduce() as well.

2. Counting Occurrences of Items in an Array Using reduce()

Another simple use for JavaScript reduce() is to obtain the number of times each item appears inside an array collection.

For example, here is the code for getting the total number of occurrences for each fruit in an array of fruits:

1
const fruits = [ 'Banana', 'Orange', 'Apple', 'Orange', 'Pear', 'Banana']
2
3
const occurrences = fruits.reduce((acc, currFruit) => {
4
    return {...acc, [currFruit]: (acc[currFruit] || 0) + 1 }
5
}, {})
6
7
console.log(occurrences)
8
9
/*

10
{

11
  Apple: 1,

12
  Banana: 2,

13
  Orange: 2,

14
  Pear: 1

15
}

16
*/

Note that at each step of the iteration, the accumulator will be a hash map (i.e. a JavaScript object) with a key for each fruit in the array so far, and the values will be the number of times each fruit has occurred. This is the expression where we update the accumulator:

1
{...acc, [currFruit]: (acc[currFruit] || 0) + 1 }

Let's break this down a little. First, using the spread operator, ...acc copies over all the existing values from the accumulator.

Then, [currFruit]: sets the value for the current fruit in the array. For example, on the very first iteration over the fruits collection, this will create the Banana property. acc[currFruit] || 0 retrieves the value for that fruit from the previous version of the accumulator. If the fruit doesn't exist in the accumulator, it will start with a value of zero. 

Finally, we add 1 to the value of that fruit and return the new accumulator.

3. Converting Between Types Using reduce()

You can also reduce an array to any other data type.

For example, suppose we want to get just the names of each student from an array of objects. We can reduce the array from an array of objects to an array of string values, like so:

1
const students = [
2
    { name: "Kingsley", score: 70 },
3
    { name: "Jack", score: 80 },
4
    { name: "Joe", score: 63 },
5
    { name: "Beth", score: 75 },
6
    { name: "Kareem", score: 59 },
7
    { name: "Sarah", score: 93 }
8
]
9
10
const names = students.reduce((acc, student) => [...acc, student.name], [])
11
12
console.log(names)
13
14
// Prints ["Kingsley", "Jack", "Joe", "Beth", "Kareem", "Sarah"]

In the code above, we accessed just the names on each iteration, and passed each name into the accumulated array using the spread operator. Since an array literal was set as the initial value, it was used as the wrapper for the final values.

Normally, we'd use map() for this use case, but I wanted to show you how we can do almost anything with reduce(). In many ways, the JavaScript reduce method is like the map method, but on steroids.

In the following example, we will reduce a students array to a single object:

1
const studentsArray = [
2
    { name: "Kingsley", score: 70, position: "1st" },
3
    { name: "Jack", score: 80, position: "2nd" },
4
    { name: "Joe", score: 63, position: "3rd" },
5
    { name: "Beth", score: 75, position: "4rd" },
6
    { name: "Kareem", score: 59, position: "5th" },
7
    { name: "Sarah", score: 93, position: "6th" }
8
]
9
10
11
const studentObj = studentsArray.reduce((acc, student) => {
12
	return {...acc, [student.name]: student.position}
13
}, {})
14
15
console.log(studentObj)
16
17
/*

18
{

19
  Beth: "4rd",

20
  Jack: "2nd",

21
  Joe: "3rd",

22
  Kareem: "5th",

23
  Kingsley: "1st",

24
  Sarah: "6th"

25
}

26
*/

Here, we restructured our data collection from an array of objects into a single object.

4. Getting Max and Min Values From an Array Using reduce()

You can easily obtain the maximum and minimum numerical values from an array in a few lines of code, using JavaScript reduce().

For example, we can obtain the maximum score from a list of scores, like so:

1
const students = [
2
    { name: "Kingsley", score: 70 },
3
    { name: "Jack", score: 80 },
4
    { name: "Joe", score: 63 },
5
    { name: "Beth", score: 75 },
6
    { name: "Kareem", score: 59 },
7
    { name: "Sarah", score: 93 }
8
]
9
10
const max = students.reduce((acc, student) => {
11
    if(acc === null || student.score > acc) 
12
        return student.score
13
    return acc
14
}, null)
15
16
console.log(max) // Prints 93

In the code above, at each iteration step we check if the current score value is greater than the accumulated value, or if the accumulator is null. If so, we update the accumulator with the new high score.

In other words, we just return the highest score so far at each step.

Conversely, in the following example, we'll be obtaining the minimum value instead:

1
const min = students.reduce((acc, student) => {
2
    if (acc === null || student.score < acc) {
3
        return student.score
4
    } 
5
    return acc
6
}, null)
7
8
console.log(min) // Prints 59

The only difference between this and that of max is the change in operator—from greater than to less than. 

5. Flatten a List of Arrays Using reduce()

The reduce() method has another handy use: flattening nested arrays.

For example, we can flatten a list of arrays into a single array, like so:

1
const arrOfArrs = [
2
    ['aaron', 'ake', 'anna', 'aje'],
3
    ['becky', 'ben', 'bright'],
4
    ['cara', 'chris'],
5
    ['david', 'daniel', 'danielle', 'djenue'],
6
]
7
8
const flattened = arrOfArrs.reduce((acc, array) => acc.concat(array))
9
10
console.log(flattened)
11
12
// ["aaron", "ake", "anna", "aje", "becky", "ben", "bright", "cara", "chris", "david", "daniel", // "danielle", "djenue"]

In this snippet, we just concatenate each array into the accumulator, merging them into a single array.

Conclusion

The JavaScript reduce() is an in-built array method used to perform an accumulative action on an array.

The method has a wide array of uses, from summing up values to flattening array lists.

Though the method is very versatile and can be used in many cases, it is important to consider other specialized methods for specific tasks: like using find() to find an item or map() to transform each of the elements in an array.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.