Angular - 如何使用 sum 和 group by
问题描述:
我需要根据 ID 对记录进行分组并显示权重总和.有人可以让我知道 Angular 中的总和和分组方法.
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 响应:
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 }
]
答
您可以使用 Array.reduce()
迭代和 Array.find()
查找按 id 的项目.然后您可以按如下方式计算总和:
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)