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 } ]