In RxJS, the
reduce operator is used to apply an accumulation function to the values emitted by an observable sequence and emit a single accumulated result. It is similar to the
Array.prototype.reduce() function in JavaScript.
The
reduce operator takes an accumulator function and an optional seed value as its parameters. The accumulator function is called for each value emitted by the source observable, and it accumulates the intermediate result based on the previous accumulated value and the current value from the source. The accumulated value is then emitted as the final result when the source observable completes.
Here's the general syntax of the reduce operator:
const $reduceOperator = from([1,2,3,4]).pipe(
reduce((sum,num) => {
return sum+num;
})
);
$reduceOperator.subscribe(data=> {
console.log('reduce operator data', data);
})
// output
// reduce operator data 10
Note: In reduce operator, intermediate result is not emitted and only the final result is emitted, while in scan operator intermediate result is emitted.
Conclusion:
The
reduce operator is useful when you want to obtain a single accumulated result from a sequence of values. It is commonly used for calculations that produce a final output, such as summing values, finding the maximum or minimum, or performing any other reduction operation on the emitted values.