5 Practical Ways to Use the JavaScript Array reduce() Method

5 Practical Ways to Use the JavaScript Array reduce() Method

Want to learn about ways to use JavaScript reduce(), I'll show you five of them here

Kingsley Ubah's photo
Kingsley Ubah
ยทSep 29, 2021ยท

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Getting the count of an array with JavaScript reduce()
  • Getting the minimum and maximum values in a JavaScript array
  • Changing data structures with reduce()
  • Sum a particular object property with JavaScript reduce()
  • Wrapping Up

Many times, the JavaScript array reduce() method gets pigeon-holed into being a function that can add up or multiply all the numbers in the array.

Here, for example, we have a list of scores in an array. Within the reduce() method we pass in a callback function that takes the accumulated value and adds it to the active number in the array, giving us the sum of the numbers at the end of the loop:

const scores = [90, 30, 6, 23, 78, 30, 27, 85]

let total = scores.reduce((acc, el) => 
acc + el, 0)

console.log(total); // 369

An illustration of javascript reduce

In actuality, reduce() can do so much more. In this tutorial, we're going to look at four other examples of what is we can do with the reduce() array method.

Getting the count of an array with JavaScript reduce()

Getting the count of a Javascript array is something you can do in a variety of ways, but perhaps none of those methods is as short as with the reduce() function:

const cart = [
  { id: "1", product_name: "tooth brush", price: "300" },
  { id: "2", product_name: "body lotion", price: "150" },
  { id: "3", product_name: "home slippers", price: "90" },
  { id: "4", product_name: "battery", price: "40" }
]

let count = cart.reduce((acc, item) => acc + 1, 0);

console.log(count); //4

Here we have a list of items in our cart array and we want to get its count. As the second argument to reduce(), we set the initial value to 0. Then on each iteration, we simply increment this number until the last item in the cart.

So if you have a list of elements in an array that you want to quickly get the count of, use reduce().

Getting the minimum and maximum values in a JavaScript array

Another use case for reduce() is to get the biggest and least number from an array.

Take the following for example:

const scores = [90, 30, 6, 23, 78, 30, 27, 85]

let min = scores.reduce((acc, score) => [Math.min(acc, 
score)], [100])

console.log(min); // [6]

We passed an empty array as a second parameter to reduce(), this will wrap the final returned value inside an array object, because [ ] + 6 is equal to [6].

On every cycle, we compare the current score with the score from the accumulator and return the smaller score for the next iteration. So in the end, we'll come up with the lowest number. The initial value is set to 100, to ensure that the first comparison, 100 and 90, returns 90 (i.e. the lesser). In the next iteration, 90 is compared to 30, and 30 is returned for the next iteration, and so on until we get the absolute smallest number.

To get the biggest number from the array, we do the opposite:

const scores = [90, 30, 6, 23, 78, 30, 27, 85]
let max = scores.reduce((acc, score) => [Math.max(acc, 
score)], [0])

console.log(max); // [90]

Math.max() returns the bigger of two numbers, so in the first iteration 90 is compared to 0, and 90 is returned for the next iteration and so on.

If you ever face a situation where you want to get either the maximum or minimum number from an array, consider using reduce()

Changing data structures with reduce()

Suppose we have an array comprising of a list of students, and we want to transform it to some kind of dictionary that allows us to look up each student by their id.

We can use reduce() to transform from an array collection to a dictionary:

const students = [
    {
      studentId: 1,
    name: 'Sam',
    grade: 3
  },
  {
      studentId: 2,
    name: 'Joe',
    grade: 6
  },
  {
      studentId: 3,
    name: 'Nkem',
    grade: 8
  },
  {
      studentId: 4,
    name: 'Aliyah',
    grade: 2
  },
  {
      studentId: 5,
    name: 'Rebecca',
    grade: 9
  },
]

var studentObj = students.reduce(function(acc, student){
    return {...acc, [student.studentId]: student}
}, {})

This time we want to wrap the resultant values inside an object. For that reason, we pass an empty object as the initial value.

Every time we loop over a student, we use the spread operator to place the student's studentId as property and its entire object as its value then we return the object for the next iteration. We use the array syntax to compute the student id properties.

Don't know what a spread operator is? check out my tutorial on the topic.

The result is a JavaScript object, studentObj. This takes the form of a dictionary comprised of a student's id as key and the student's entire information as value.

/*
{
  1: {
    grade: 3,
    name: "Sam",
    studentId: 1
  },
  2: {
    grade: 6,
    name: "Joe",
    studentId: 2
  },
  3: {
    grade: 8,
    name: "Nkem",
    studentId: 3
  },
  4: {
    grade: 2,
    name: "Aliyah",
    studentId: 4
  },
  5: {
    grade: 9,
    name: "Rebecca",
    studentId: 5
  }
}
*/

We can look up a particular student in the dictionary by his or her id:

console.log(studentObj[1]);

/*
{
  grade: 3,
  name: "Sam",
  studentId: 1
}
*/

If you ever want to change from kind one data structure to another with minimal code, consider using reduce().

Sum a particular object property with JavaScript reduce()

Let's go back to our cart array in the first example.

const cart = [
  { id: "1", product_name: "tooth brush", price: 300 },
  { id: "2", product_name: "body lotion", price: 150 },
  { id: "3", product_name: "home slippers", price: 90 },
  { id: "4", product_name: "battery", price: 40 }
]

In the end, you may need to sum up the price to present a bill for your customer.

You can sum up the price fields like so:

const cart = [
    { id: "1", product_name: "tooth brush", price: 300 },
  { id: "2", product_name: "body lotion", price: 150 },
  { id: "3", product_name: "home slippers", price: 90 },
  { id: "4", product_name: "battery", price: 40 }
]

let totalAmount = cart.reduce((acc, item) => acc + item.price, 0);

console.log(totalAmount); //580

As we cycle through the array, the price is accumulated. The beauty of using reduce is that you achieve this in just one line of code.

Wrapping Up

That's it, five examples showing the practical usage of the JavaScript reduce() method in our code.

If you have any questions regarding this topic, feel free to leave them in the comments.

Have a great weekend.

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 .

ย 
Share this