将angular4与rxjs 5.4.0
一起使用我正在尝试按“类型”对列表进行分组并获取其计数。有人可以帮忙吗?以下是我的代码
export class Sample{
type:string;
data:any ...
...
}
我有一个Sample Class
数组list:Sample[] = // number of elements
Observable.from(this.list).groupBy(x=> x.type)
.flatMap( group => {
return group.reduce; // how can i use reduce function to count numbers and return map of type and their count
}
})
答案 0 :(得分:3)
你很接近,我认为你只需要在分组的可观察数据上再多运算一次。
const list = [{ type: 'foo' }, { type: 'bar' }, { type: 'bar' }];
Observable.from( list ).groupBy( x => x.type )
.mergeMap( list$ => { // each emission is a stream
/* A stream of "aggregated" data. */
const count$ = list$.count();
/* Format the result. */
return count$.map( count => ({ type: list$.key, count }));
});
这会发出:
{ type: 'foo', total: 1 }
{ type: 'bar', total: 2 }
听起来你可能有更复杂的用例来计算“聚合”,也许你需要总结Sample.data
。如果是这样,您只需要使用自己的count$
实现更改。假设data
是一个数字列表:
const list = [{
type: 'foo',
data: [1,2,3]
}, {
type: 'bar',
data: [4,5,6]
}, {
type: 'bar',
data: [7,8,9]
}];
Observable.from( list ).groupBy( x => x.type )
.mergeMap( list$ => { // each emission is a stream
/* A stream of "aggregated" data. */
const count$ = list$.reduce( ( accumulator, sample ) => { // reduce the stream
return accumulator + sample.data.reduce( ( acc, datum ) => { // reduce the array
return acc + datum;
}, 0);
}, 0);
/* Format the result. */
return count$.map( count => ({ type: list$.key, count }));
});
这会产生:
{ type: 'foo', total: 6 }
{ type: 'bar', total: 39 }