2017-09-25 177 views
0

使用angular4和rxjs 5.4.0angular2 rxjs groupby with count

我想按'类型'对列表进行分组并获取它们的数量。有人可以帮忙吗?下面是我的代码

export class Sample{ 
    type:string; 
    data:any ... 
    ... 
} 

我有样例类

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 
    } 
}) 

回答

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 } 
+2

您可以简化这一点,因为与该分组由该值可通过'key'财产上的[ 'GroupedObservable'](http://reactivex.io/rxjs/class/es6/operator/groupBy.js~GroupedObservable.html)。也就是说,你不需要使用'list $ .take(1).map(x => x.type)'来获得它;只需使用'list $ .key'。 – cartant

+0

非常棒,谢谢。我已经更新了答案。 – xtianjohns