Search code examples
angulartypescriptangular7

Angular - How to use sum and group by


I need to group the records based on ID and display sum of weight. can someone please let me know the sum and group by method in Angular.

API Response:

data = [
  {Id:1, name: 'ABC', weight: 10 },
  {Id:1, name: 'ABC', weight: 14 },
  {Id:1, name: 'ABC', weight: 16 },
  {Id:2, name: 'DEF', weight: 23 },
  {Id:2, name: 'DEF', weight: 22 },
  {Id:4, name: 'GHI', weight: 44 },
  {Id:4, name: 'GHI', weight: 41 }
]

Expected output:

dataResult =  [
      {Id:1, name: 'ABC', weight: 40 },
      {Id:2, name: 'DEF', weight: 45 },
      {Id:4, name: 'GHI', weight: 85 }
    ]

Solution

  • You can use Array.reduce() to iterate over and Array.find() to find item by id. Then you can calculate the sum as followings:

    const data = [
      {Id:1, name: 'ABC', weight: 10 },
      {Id:1, name: 'ABC', weight: 14 },
      {Id:1, name: 'ABC', weight: 16 },
      {Id:2, name: 'DEF', weight: 23 },
      {Id:2, name: 'DEF', weight: 22 },
      {Id:4, name: 'GHI', weight: 44 },
      {Id:4, name: 'GHI', weight: 41 }
    ]
    
    const calculated = data.reduce((acc, item) => {
      
      let accItem = acc.find(ai => ai.Id === item.Id)
      
      if(accItem){
          accItem.weight += item.weight 
      }else{
         acc.push(item)
      }
    
      return acc;
    },[])
    
    console.log(calculated)