A reduction combines a sequence of values into one accumulated result. Its reducer receives the current result and the next value, then returns the result carried into the next step. section 4.3.1
The result and timing depend on what is being reduced:
- With an array, reduce folds values into one result; summing [1, 2, 3, 4, 5, 6] produces 21. section 4.3.1
- With an observable, reduce accumulates emitted values and emits one result when the source completes. section 9.4.3
- A reducer can also combine functions: repeated composition folds a list of functions into one composed function. section 4.3.1
const sum = (a,b) => a + b; [1,2,3,4,5,6].reduce(sum); // 21
See the array reduction example, where sum accumulates six numbers into 21. section 4.3.1
Listing 9.22 Custom reduce operator
const reduce = curry(
(accumulator, initialValue, stream) => {
let result = initialValue ?? {}; #1
return new Observable(observer => {
const subs = stream.subscribe({
next(value) {
result = accumulator(result, value); #2
},
error(e) {
observer.error(e);
},
complete() {
observer.next(result); #3
observer.complete(); #3
}
})
return () => subs.unsubscribe();
});
};
);
See a custom observable reduce operator that updates an accumulator and emits it on completion. section 9.4.3








