- RxJS Tutorial
- RxJS - Home
- RxJS - Overview
- RxJS - Environment Setup
- RxJS - Latest Updates
- RxJS - Observables
- RxJS - Operators
- RxJS - Working with Subscription
- RxJS - Working with Subjects
- RxJS - Working with Scheduler
- RxJS - Working with RxJS & Angular
- RxJS - Working with RxJS & ReactJS
- RxJS Useful Resources
- RxJS - Quick Guide
- RxJS - Useful Resources
- RxJS - Discussion
RxJS - Mathematical Operator Reduce
In reduce operator, accumulator function is used on the input observable, and the accumulator function will return the accumulated value in the form of an observable, with an optional seed value passed to the accumulator function.
The reduce() function will take in 2 arguments, one accumulator function, and second is the seed value.
Syntax
reduce(accumulator_func, seeder?) : Observable
Parameters
accumulator_func − (optional). a function that is called on the source values from the observables.
seeder − ((optional) By default it is undefined. The initial value to considered for accumulation.
Return value
It will return an observable that will have a single accumulated value.
We will see some examples to see how the reduce operator works.
Example 1
import { from } from 'rxjs'; import { reduce } from 'rxjs/operators'; let items = [ {item1: "A", price: 1000.00}, {item2: "B", price: 850.00}, {item2: "C", price: 200.00}, {item2: "D", price: 150.00} ]; let final_val = from(items).pipe(reduce((acc, itemsdet) => acc+itemsdet.price, 0)); final_val.subscribe(x => console.log("Total Price is: "+x));
Output
Total Price is: 2200
Advertisements