问题
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