The JavaScript Reduce Method

Simplify the way you calculate the total value in an array

Introduction

The JavaScript reduce method is one of the higher order functions introduced in es6 which allows us to "reduce" the values inside of an array into a single value. Today, we will be taking a look at how to implement this in our code.

Getting Started

The .reduce() method is a higher order function that can be called on any array -- see below:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce();

Like all the other array methods .reduce() loops through your entire array. The difference here is that .reduce() is a function has two parameters, one being a function while the other is the initial value of what we call and accumulator -- this is the thing that will increment at every iteration of the loop.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce(() => {}, 0);

The function inside reduce, takes in two parameters itself, one being an accumulator while the other being the value of the current position in the array. See Below:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce((acc, curr) => {}, 0);

To update the accumulator at each iteration we must add a return it inside the function. We can assign this function to a variable which can then be used for anything.

Using Reduce: Example

Lets say we have an array from 1 - 10 and we need to add all the elements in the array to determine the total, we can use the reduce method to accomplish this -- We can call the reduce method on our array, setup the accumulator and current parameters and also pass in an initial value of 0.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce((acc, curr) => {
  return acc + cur;
}, 0);

Using reduce: Another Example

Going over out class object that we created (link to other post), lets say we wamted to calculate the average for the class. We can either write a while loop or for loop to accomplish this or we can use the reduce method.

Here is an array of objects where each object represents a student in the class.

const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

Using the reduce method:

const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

const TotalMarks = students.reduce((acc, curr) => acc + cur, 0);
const averageMark = TotalMakrs / students.length;
console.log(averageMark);

Now that this is complete, we have a way to reduce an array into a single value without writing our own loop!

Question for you

Now knowing this, here's a question for you -- how else can we implement the reduce method?


Check out the youtube channel to see how we are implementing the feature in the app we are building! theYoutubeChannel