Angular - 如何使用 sum 和 group by [英] Angular - How to use sum and group by
本文介绍了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)
这篇关于Angular - 如何使用 sum 和 group by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文