【问题标题】:Angular - How to use sum and group byAngular - 如何使用 sum 和 group by
【发布时间】:2020-09-03 22:59:35
【问题描述】:

我需要根据 ID 对记录进行分组并显示重量总和。有人可以让我知道 Angular 中的总和和按方法分组吗?

API 响应:

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

预期输出:

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

【问题讨论】:

标签: angular typescript angular7


【解决方案1】:

您可以使用 Array.reduce() 进行迭代,并使用 Array.find() 按 id 查找项目。然后您可以按以下方式计算总和:

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)

【讨论】:

  • 谢谢,您的解决方案对我有用。是否可以基于两列进行分组。在 find 中我们可以使用两列吗?
  • 不客气。很高兴听到它对你有用。当然也可以在find():acc.find(ai => ai.Id === item.Id && ai.name === item.name)等中展开条件语句
【解决方案2】:

我用 JavaScript 写的,你可以很容易地把它转换成 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2021-01-30
    • 2021-05-09
    相关资源
    最近更新 更多