- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Aggregate records in JavaScript
Let’s say, we have an array of objects that contains information about some random transactions carried out by some people −
const transactions = [{ name: 'Rakesh', amount: 1500 }, { name: 'Rajesh', amount: 1200 }, { name: 'Ramesh', amount: 1750 }, { name: 'Rakesh', amount: 2100 }, { name: 'Mukesh', amount: 1100 }, { name: 'Rajesh', amount: 1950 }, { name: 'Mukesh', amount: 1235 }, { name: 'Ramesh', amount: 2000 }];
We are required to write a function that takes in this array and aggregates and returns the transaction amount of unique people in distinct objects.
Therefore, let’s write the code for this function −
Example
const transactions = [{ name: 'Rakesh', amount: 1500 }, { name: 'Rajesh', amount: 1200 }, { name: 'Ramesh', amount: 1750 }, { name: 'Rakesh', amount: 2100 }, { name: 'Mukesh', amount: 1100 }, { name: 'Rajesh', amount: 1950 }, { name: 'Mukesh', amount: 1235 }, { name: 'Ramesh', amount: 2000 }]; const aggregateArray = arr => { return arr.reduce((acc, val) => { const index = acc.findIndex(obj => obj.name === val.name); if(index !== -1){ acc[index].amount += val.amount; }else{ acc.push({ name: val.name, amount: val.amount }); }; return acc; }, []); }; console.log(aggregateArray(transactions));
Output
The output in the console will be −
[ { name: 'Rakesh', amount: 3600 }, { name: 'Rajesh', amount: 3150 }, { name: 'Ramesh', amount: 3750 }, { name: 'Mukesh', amount: 2335 } ]
- Related Articles
- MongoDB Aggregate to limit the number of records
- Difference between Aggregate Demand and Aggregate Supply
- What records are present in JavaScript cookies?
- Aggregate method in C#
- Aggregate Functions in DBMS
- Get substring in MongoDB aggregate
- Using $redact in MongoDB aggregate?
- C# Aggregate() method
- Remove/ filter duplicate records from array - JavaScript?
- What is aggregate demand?
- Using an Aggregate function in SAP HANA
- How to update after aggregate in MongoDB?
- How to aggregate array documents in MongoDB?
- Implement $match and $project in MongoDB aggregate
- MongoDB aggregate query to sort

Advertisements