Ole
Ole

Reputation: 46960

Counting by property state using RxJS?

Suppose we wish to create an observable that emits a count. For example we may have a let todos:Observable<todo[]> and we wish to know how many of those instances have the completed property set to true. So:

 let count = todos.pipe() //do the count

Upvotes: 2

Views: 556

Answers (1)

cartant
cartant

Reputation: 58400

The todos observable emits values that are arrays of todos, so you can use the map operator to map the array to the number of completed todos that it contains.

To count the number of completed todos, you can use Array.prototype.reduce within the map operator:

import { map } from 'rxjs/operators';
// ...
const completed = todos.pipe(
  map(ts => ts.reduce(
    (total, t) => total + (t.completed ? 1 : 0),
    0
  ))
);

Upvotes: 1

Related Questions