2017-09-25 178 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