BACK
ПрактикаReal-life: groupBy() totals by account
ПРАКТИКА · 55 · 練

Real-life: groupBy() totals by account

Сгруппируйте платежи по account и посчитайте сумму каждой группы.

  1. Решите задачу в редакторе без длинной теории.
  2. Запустите проверку и сравните вывод с ожидаемым.
  3. Если застряли, откройте решение и перенесите подход в свой код.
Решение spoiler · click to reveal
const { from, groupBy, mergeMap, reduce, map } = Rx;

const payments = [
  { account: 'A', amount: 10 },
  { account: 'B', amount: 5 },
  { account: 'A', amount: 7 },
];

const result$ = from(payments).pipe(
  groupBy(payment => payment.account),
  mergeMap(group$ => group$.pipe(
    reduce((sum, payment) => sum + payment.amount, 0),
    map(sum => group$.key + ':' + sum)
  ))
);

result$.subscribe(value => console.log(value));
script.ts // TypeScript
CONSOLE · Console Output
Нажмите на запуск, чтобы увидеть результат...