There are different high-order array methods in JavaScript, and we have discussed most of them in the past few weeks. But there is this particular high-order array method that was really difficult for me to grasp at first and I did not even know if I was going to ever use it in any real-world project. That array method is the reduce()
method. And in this article, we will be discussing what it is, how it works and the use cases too. So let’s dive right into it.
What is reduce()
method?
The reduce()
method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
Yea, I know that was a lot of grammar, so let’s see an easier explanation of what the reduce()
method is 👇🏽
The reduce()
method simply takes an array of values, iterates through them, and reduces it down to one single value.
Let’s see an example 👇🏽
const ages = [2, 10, 12, 4, 6];
const totalAge = ages.reduce((total, age) => {
return total + age;
}, 0);
console.log(totalAge); // 34
If you are familiar with the high-order array methods such as forEach()
, filter()
, map()
etc. You will notice a pattern and the only difference in this example is the 0
, which is what we are going to talk about in a moment. So let’s break things into steps using the example which just created.
Step 1
In the example above, we called the reduce()
method on the ages
array. And the reduce method takes in two different parameters. The first parameter is the arrow function
👇🏽
ages.reduce(() => {});
and the second parameter is what we called the starting point
which in our case is the 0
(and this can be anything at all, is not just limited to a single value) 👇🏽
ages.reduce(() => {
}, 0);
Step 2
In this second step, we will talk about the different parameters that are inside the arrow function
. The arrow function
(which is the first parameter) has four different parameters.
The first one is called the accumlator
which in the example is the total
and it is called the accumlator
because it is what we are reducing our values down to.
The second parameter is just each individual age
that we iterated over.
The third parameter is the index
and the fourth parameter is the array
.
The third and fourth parameters are not really important because you will always the first two parameters 99% of the time as seen in the example.
Just a side note, you can decide to give these parameters any name you want. You only need to just know what their function is.
Here is a visual example of the four parameters 👇🏽
ages.reduce((total, age, index, array) => {
}, 0);
Now that we understand what the parameters are for the reduce
method, let’s go a little deeper to see how it works.
How the reduce()
method works
The way the reduce()
method works (still using the first example) is that the default value which is 0
, will pass through the accumulator
(which is the total
) the very first time we go through our loop.
So our total
will be 0
at first, and whatever we return from reduce()
is going to be our total
for the next iteration. And when there is nothing to iterate over, the ages
array will be reduced down to a total
price.
Let’s see this part from the example again for a clearer understanding 👇🏽
const ages = [2, 10, 12, 4, 6];
const totalAge = ages.reduce((total, age) => {
return total + age;
}, 0);
console.log(totalAge); // 34
If you are still confused about how the reduce()
method works, let’s see in detail what is happening under the hood by console logging out the total
and each age
using the same example 👇🏽
const ages = [2, 10, 12, 4, 6];
const totalAge = ages.reduce((total, age) => {
console.log(`Total: ${total}`);
console.log(`Age: ${age}`);
return total + age;
}, 0);
console.log(totalAge);
Here is the output for the code above 👇🏽
In the code output above, you will notice that the total
price is 0
because that was what we used as our starting point
and our age
is 2. On the next iteration, our total
will then be 2 because it is what we are returning. That is how it is going to iterate through all the values in the ages
array.
One thing to note about reduce
is that, whatever you return from the reduce
function will be the value for total
on the next iteration, and when there is nothing to loop through, whatever you return on your last iteration is going to be what returns on the variable (which is totalAge
as used in the example) that you set for the reduce function.
Let’s see another example 👇🏽
const result = [
{ name: 'James', score: 41 },
{ name: 'Mattew', score: 59 },
{ name: 'Judith', score: 36 },
{ name: 'John', score: 90 },
{ name: 'Mark', score: 64 },
];
let initialValue = {
pass: [],
fail: [],
};
const groupedResult = result.reduce((total, cummulative) => {
const score = cummulative.score;
if (score >= 50) {
total.pass.push(cummulative);
} else {
total.fail.push(cummulative);
}
return total;
}, initialValue);
console.log(groupedResult);
Yes I know you must be thinking that this is a little bit advanced from the previous example we did earlier. But the truth is that there is not much difference at all.
Let’s see what is going on in the example.
Here, We created a result
object array with five objects, and each object has name
and score
as its properties.
After that, we also created the initialValue
object that has pass
and fail
as its properties and also assigned an empty array to both of the properties. And if you notice, you will see that we used the let
keyword because we are using the initialValue
as our starting point.
Next, we created the groupedResult
variable, that we set our reduce function to.
Now, let’s see what is happening inside the reduce function.
We first of all created score
variable to get the score
for each person (name
).
We then created an if statement, and what it does is that thename
is passed if score
is greater than or equal to 50. Otherwise the name
fails. So we are simply using thereduce()
to group the result into the pass and fail array.
The initialValue
is assigned to the total
, then the push()
method adds the cummulative
object to the pass
and the fail
properties as object arrays after checking the condition.
In case you are wondering what the push()
method does?
The push()
method simply adds one or more elements to the end of an array and returns the new length of the array.
Here is the output of the example we just talked about 👇🏽
The output looks pretty straightforward because the pass
and fail
that has an empty array has been populated based on the condition we set it to.
Conclusion
Congrats, I really hope you now understand the basics of what the reduce
array is and how it works. I realized that the article was really getting a bit lengthy and we did not cover some things such as some of the use cases of thereduce
method. So here is a link to part 2 that covers that aspect 👇🏽
4 Use Cases for reduce() in JavaScript
You can also push yourself by trying to make changes to the example we did and add your stuff to it. Here is the link to the GitHub repo of the examples we did and I also added some extra examples to it too.
https://github.com/dev-lawrence/Array-methods
See you next week Friday 😀