I've been struggling to come up with a way to create a grouped and summarized array of values (to be used with ngFor) from a list of objects, but I just can't seem to get it right. The data, which is a subset of my state, is structured like this:
[{name: "A", value: 1, desc: 'something irrelevant'},
{name: "A", value: 3, desc: 'also other properties'},
{name: "B", value: 2, desc: 'etc.'},
{name: "B", value: 5, desc: 'etc.'}]
The desired result that I'm aiming for is something similar to (note the different data type):
[{name: "A", value: 4}, {name: "B", value: 7}]
In essence, I want to identify the unique "names" and calculate the total "value" for all objects with that name, in a format suitable for ngFor | async.
My solution that I got close to working is:
this.aggregates:Observable<any[]> = this.store
.select(state => state.valuesList)
.map(valuesList => valuesList.sort((a,b) => {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} }))
.flatMap(valuesList => valuesList)
.map(value => value.name)
.distinct();
I'm fine with this start, yet the issue arises when I try to use toArray(). If I skip it, Typescript throws an error "Type string is not assignable to type any[]"; when I include toArray() after distinct(), no results are returned upon subscribing.
What am I missing here? Should I consider moving this logic to the reducer, even though I'm uncertain if I can change the type of objects returned by different actions within the same reducer? Any guidance would be greatly appreciated.
UPDATE: I would greatly appreciate a functioning implementation of groupBy(), as it seems to perfectly fit this scenario.