Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
Scan a stream of objects and add a property with the running sum in RxJS

Assuming I have a source stream of objects as follows:

source$ = from([{ id: 1, cost: 10},{ id: 2, cost: 5},{ id: 3, cost: 3},{ id: 4, cost: 10}])

In the derived observable I would like maintain an additional property with a running sum of the cost

// Expected derived stream
{ id: 1, cost: 10, totalCost: 10}
{ id: 2, cost: 5,  totalCost: 15}
{ id: 3, cost: 3,  totalCost: 18}
{ id: 4, cost: 10, totalCost: 28}

How could it be achieved with rxjs?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I managed to find this solution:

import { from } from "rxjs";
import {scan} from "rxjs/internal/operators";

let source$ = from([{ id: 1, cost: 10},{ id: 2, cost: 5},{ id: 3, cost: 3},{ id: 4, cost: 10}]);


source$
.pipe(
  scan((acc,curr) => {
      return {...curr, totalCost: acc.totalCost + curr.cost}
  }, {totalCost:0})
) 
.subscribe(console.log)

https://codesandbox.io/s/rxjs-playground-forked-3bdpd

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!