This article will show you a few examples of how to use reduce method in JavaScript / TypeScript
The best way to learn the reduce method in my opinion is through going through various examples so let’s jump right into it and see the first coding example. on below I’ve initialized a list of objects, and I want to iterate through it using the reduce function. let’s see how we do that:
const moviesList = [
{ movie: 'Avengers', ticketCost: 11.99},
{ movie: 'Harry Potter', ticketCost: 10.99},
{ movie: 'Justice League', ticketCost: 4.99},
{ movie: 'The Tomorrow War', ticketCost: 8.99},
{ movie: 'Assassins Creed', ticketCost: 6.99}
]
let totalCost = 0;
moviesList.forEach( (item)=> {
totalCost += item.ticketCost;
});
console.log(totalCost);
Firstly, I’ve initialized a list of objects called “movieList” in which I have five objects, each containing a name of a movie and the cost of its ticket. What I want to do here is, to sum up, all the cost of the tickets and print that out. The “item” parameter is fetching each record from the list and the variable “totalCost” is adding up the ticketCost inside each object. Lastly, it’s printing the value “totalCost”. If you’re still unfamiliar or still confused on how forEach() loop works, check out this article here. This will get you a good understanding of how forEach() works. Now let’s check how we use reduce() method to do the same thing.
const moviesList = [
{ movie: 'Avengers', ticketCost: 11.99},
{ movie: 'Harry Potter', ticketCost: 10.99},
{ movie: 'Justice League', ticketCost: 4.99},
{ movie: 'The Tomorrow War', ticketCost: 8.99},
{ movie: 'Assassins Creed', ticketCost: 6.99}
]
const totalCost = moviesList.reduce( (total, item)=>{
return total + item.ticketCost;
}, 0);
console.log(totalCost);
So, let’s breakdown what’s happening in here. At line number 10, it shows that the reduce method takes in two parameters. The first parameter is a function on its own and the next parameter is a default parameter that’s 0 here and it’s what the value of “total” will start off with when beginning to traverse the list.
As you can see the first parameter is a function, which takes two parameters in itself. Of which the first is the “total” variable (also called the accumulator) and the other is the “item” (which is the same for when we pass in the forEach() loop function). The value of the “total” variable gets renewed in each iteration and the “item” variable basically fetch each record from the list in each iteration. The default value, which is 0, is the starting value given to the variable “total”, and then in each iteration, whatever value that is being returned, is then saved into the “total” variable. Finally, when all the items have been iterated through, the last returned value would be stored into the external variable called “totalCost”, which is then printed later.
Now let’s talk about that default value, what it is and what it means. So, the default value should not necessarily be an integer. It can be an empty curly brace {}, representing an empty object or it could be a string, or it can be any of the data type you want it to be. thing to remember is that whatever the default value is set, that’s what’s going to be stored as a value into the first parameter of the function. So, let’s say you want to count through some integers and the default value is set to let’s say 100. Whatever the count should have been, it would be 100 more than the actual count because it started off from 100 and not 0.
Let’s look at another example and this time let’s make the default value an empty object.
const names = [
{name: "Sam", age: 22},
{name: "Tam", age: 35},
{name: "Pam", age: 27},
{name: "Ham", age: 22}
];
const finalList = names.reduce( (total, item)=> {
const age = item.age;
if(total[age] == null) { total[age] = [item] }
else { total[age].push(item); }
return total
}, {} );
console.log(finalList);
So, in the above code I’ve initialized another list containing names and age of people which I’ve I traversed through using reduce method. The goal of the above code is to group the objects having the same age into one list. And as you can see the default parameter is set to be an empty object which means the final printed output would also be an object. And according to the output shown in the image on the right side, it has done exactly that. Let’s understand the logic behind the code.
The first parameter which is “total”, starts off with an empty object and then it checks if there exists any record against key ‘age’ in the “total” parameter. If it does find’s it, it appends to the inner list which is the value in the key value pair. Whereas, if it doesn’t find any record against the key ‘age’ it will just add in that data as a new record.
That’s about it!
I hope this article helps you in understanding how reduce method in JavaScript works and hopefully you will be confident enough to be able to apply it in your next project. Please like and review in the comments down below and have a great one!
Recent Comments
Categories
- Angular
- AWS
- Backend Development
- Big Data
- Cloud
- Database
- Deployment
- DevOps
- Docker
- Frontend Development
- GitHub
- Google Cloud Platform
- Installations
- Java
- JavaScript
- Linux
- MySQL
- Networking
- NodeJS
- Operating System
- Python
- Python Flask
- Report
- Security
- Server
- SpringBoot
- Subdomain
- TypeScript
- Uncategorized
- VSCode
- Webhosting
- WordPress
Search
Recent Post
Understanding Mutex, Semaphores, and the Producer-Consumer Problem
- 13 October, 2024
- 10 min read
Process scheduling algorithm – FIFO SJF RR
- 14 September, 2024
- 8 min read
How to Implement Multithreading in C Language
- 8 September, 2024
- 9 min read