find sum of amount for group of list

Tags: ,



I am new to Reactjs.

I have below data

Name        Amount

Poorna     11000.00

Kumar       2900.00

Ashok       20000.00

Kumar      3020.00

Poorna     15000.00

Output should display like below

Name        Amount

Poorna     26000.00

Kumar       5920.00

Ashok       20000.00 

Please help me.

Answer

Use Array.reduce()

var sample= [
   {  Name: 'Poorna', Amount: 50},
   {  Name: 'Kumar', Amount: 50},
   {  Name: 'Ashok ', Amount: 75},
   {  Name: 'Poorna', Amount: 35},
   
];
var res = sample.reduce((a, obj)=>{
  var existItem = a.find(item => item.Name=== obj.Name);
  if(existItem){
    existItem.Amount += obj.Amount;
    return a;
  } 
  a.push(obj);
  return a;
}, []);
console.log(res);


Source: stackoverflow