Reduce, Aggregate and Flatmap Operators of Sequencing
Learn to operate the reduce, aggregate and flatMap operators of sequencing.
We'll cover the following...
Reduce
The reduce
operator, also known as fold, takes an Observable and returns a new one that always contains a single item, which is the result of applying a function over each element. This function receives the current element and the result of the function’s previous invocation.
Note: The
reduce
function has another parameter that is optional and can be used to pass a starting seed value.
var Rx = require('rx'); var src = [1,2,3,4,5]; var sum = src.reduce(function(a,b) { return a+b; }); console.log(sum);
Now let’s run the code while subscribing to the value:
var Rx = require('rx'); var logValue = function(val) { console.log(val) }; var src = Rx.Observable.range(1, 5); var sum = src.reduce(function(acc, x) { return acc + x; }); sum.subscribe(logValue);
The reduce
operator is a powerful operator that is used to manipulate a sequence. It is, in fact, the base implementation for a whole subset of methods called aggregate operators.
Aggregate operators
Aggregate operators process a sequence and return a single value. For example, Rx.Observable.first
takes an Observable and an optional predicate function and ...