DEV Community

alɔeksandyr
alɔeksandyr

Posted on

RxJS: Reduce vs Scan

Reduce operator - reduces the values from source observable to a single value that's emitted when the source completes

// RxJS v6+
import { of } from 'rxjs';
import { reduce } from 'rxjs/operators';

const source = of(1, 2, 3, 4);
const example = source.pipe(reduce((acc, val) => acc + val));
//output: Sum: 10
const subscribe = example.subscribe(val => console.log('Sum:', val));
Enter fullscreen mode Exit fullscreen mode

Scan operator - reduce over time!

// RxJS v6+
import { of } from 'rxjs';
import { scan } from 'rxjs/operators';

const source = of(1, 2, 3);
// basic scan example, sum over time starting with zero
const example = source.pipe(scan((acc, curr) => acc + curr, 0));
// log accumulated values
// output: 1,3,6
const subscribe = example.subscribe(val => console.log(val));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)