liveBook · Manning

Reduction operation

As explained in The Joy of JavaScript

A function or method that combines a collection of values into a single accumulated result.

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

How The Joy of JavaScript covers it

How deep it goes
Explains reducer callbacks, accumulation, and observable completion, with array and operator implementations.
Examples
Demonstrates summing an array, composing functions, and reducing observable values.
What it assumes
Builds from a simple sum example and explains the reducer role; assumes familiarity with functions and arrays.
What you can do after
Apply Array#reduce to accumulate values, or use a custom observable operator to emit an accumulated result on completion.
How it connects
Connects reduction to function composition, arrays, observables, and stream operators.

Also explained in

Compare how 9 books explain reduction operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.