BACK
PracticeReal-life: groupBy() totals by account
PRACTICE · 55 · 練

Real-life: groupBy() totals by account

Group payments by account and sum each group.

  1. Solve the task in the editor — no long theory.
  2. Run the check and compare your output with the expected result.
  3. Stuck? Open the solution and carry the approach into your own code.
Solution 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
Hit Run to see the result...