Angular - How to use sum and group by

我怕爱的太早我们不能终老 提交于 2021-02-20 00:24:26

问题


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

回答1:


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)



回答2:


I wrote it in JavaScript, you can easily convert it to TypeScript.

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

function entryIdAlreadyExists(dataEntries, entry) {
    for (let dataEntry of dataEntries) {
        if (entry.Id === dataEntry.Id) {
            return true;
        }
    }
    return false;
}

function updateWeightForEntryWithId (dataEntries, entry) {
    for (let dataEntry of dataEntries) {
        if (entry.Id === dataEntry.Id) {
            dataEntry.weight = dataEntry.weight + entry.weight;           
        }
    }
    return dataEntries;
}

let result = [];
for (let entry of data) {
    if (entryIdAlreadyExists(result, entry)) {
        result = updateWeightForEntryWithId (result, entry);
    } else {
        result.push(entry);
    }
}

console.log(result);


来源:https://stackoverflow.com/questions/61864621/angular-how-to-use-sum-and-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!