I use a GroupBy
pipe to group my data according to a parameter and it works very well, but I would like to add to this pipe a second parameter like this:
<li *ngFor="let object of myArray | groupByWithSum:'color':'price'">
COLOR:{{object.key}} - SUM_PRICE:{{object.sum}}
</li>
Allowing the sum of all items grouped according to an object attribute, here the price
.
Example: StackBlitz HERE
Here is my object list:
var myArray = [
{ name: "Apple", color: "Green", price: "5,999" },
{ name: "Banana", color: "Yellow", price: "6,999" },
{ name: "Grape", color: "Green", price: "12,999" },
{ name: "Melon", color: "Yellow", price: "10,999" },
{ name: "Orange", color: "Orange", price: "3,999" }
];
I want to sort this list by color and get the total sum of the prices
by color
.
And that's what I'd like to get:
[
{
key: "Green",
sum: "18,998",
value: [
{ name: "Apple", color: "Green", price: "5,999" },
{ name: "Grape", color: "Green", price: "12,999" }
]
},
{
key: "Yellow",
sum: "17,998",
value: [
{ name: "Banana", color: "Yellow", price: "6,999" },
{ name: "Melon", color: "Yellow", price: "10,999" }
]
},
{
key: "Orange",
sum: "3,999",
value: [
{ name: "Orange", color: "Orange", price: "3,999" }
]
}
];
I started a StackBlitz sorting the list by color
, but I can't make the sum. If anyone would be willing to help me.
GroupByWithSumPipe:
export class GroupByWithSumPipe implements PipeTransform {
transform(collection: object[], property: string, sum: string): object[] {
// prevents the application from breaking if the array of objects doesn't exist yet
if(!collection) { return null; }
const groupedCollection = collection.reduce((previous, current)=> {
if(!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
// this will return an array of objects, each object containing a group of objects
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
Thank you in advance.
On your return statement, you can add the sum statement:
transform(collection: object[], property: string, sum: string): object[] {
//...
return Object.keys(groupedCollection).map(key => ({
key,
sum: groupedCollection[key].reduce((a, b) => a + parseInt(b[sum]), 0),
value: groupedCollection[key]
}));
}
You are using strings for price though, I've added a parseInt
to make it work but you better just make these value numbers in your source data