RxJs 中的 GroupBy 和 Sum

iLe*_*ing 0 javascript rxjs

我无法理解使用 Lodash 可以轻松完成的事情。我需要groupBysum,像这样,只使用 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)

jsbin 在这里

Nik*_*ing 5

我现在想不出任何方法来优雅地使用 rx 解决它 - 使用 rx + lodash 好吗?

jsbin

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