我无法理解使用 Lodash 可以轻松完成的事情。我需要groupBy和sum,像这样,只使用 RxJs:
let arr = [
{n: 'a', q: 1 },
{n: 'a', q: 2},
{n: 'b', q: 4 }
];
let v = _(arr).chain().groupBy('n').map(sumQt).value()
function sumQt(x) {
return { name: x[0].n, qt: _.sum(x, 'q') }
}
// it produces array like: [{ name: "a", qt: 3 }, { name: "b", qt: 4 }]
Run Code Online (Sandbox Code Playgroud)
我现在想不出任何方法来优雅地使用 rx 解决它 - 使用 rx + lodash 好吗?
// setup
let arr = [{n: 'a', q: 1 },
{n: 'a', q: 2},
{n: 'b', q: 3 }];
function sumQt(x) {
return { name: x[0].n, qt: _.sum(x, 'q') }
}
Run Code Online (Sandbox Code Playgroud)
使用 lodash
let v = _(arr)
.chain()
.groupBy('n')
.map(sumQt)
.value()
console.log('lodash:', v)
Run Code Online (Sandbox Code Playgroud)
只使用 rx
Rx.Observable.from(arr)
.groupBy(x => x.n)
.flatMap(group => {
return group.reduce((acc, currentValue) => {
acc.n = currentValue.n;
acc.qt = acc.qt + currentValue.q;
return acc;
}, {n: undefined, qt: 0})
})
.subscribe(sum => console.log('rx:', sum));
Run Code Online (Sandbox Code Playgroud)
如果您可以使用q而不是qt
Rx.Observable.from(arr)
.groupBy(x => x.n)
.flatMap(group => {
return group.reduce((acc, currentValue) => {
acc.q = acc.q + currentValue.q;
return acc;
})
})
.subscribe(sum => console.log('rx:', sum));
Run Code Online (Sandbox Code Playgroud)
使用 rx 和 lodash
Rx.Observable.from(arr)
.groupBy(x => x.n)
.flatMap(group => group.toArray())
.map(sumQt)
.subscribe(sum => console.log('rx+lodash:', sum));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6778 次 |
| 最近记录: |