Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs6 - filter array of objects

Tags:

rxjs

I would filter array of objects using RXJS operator filter

I've array of objects like this single one:

    {
      id: string,
      count: number
    }

I would get objects which count > 20

I tried:

  getVotes2(): Observable<Vote> {
    return this._http.get<Vote>(url)
     .pipe(
       map( results => results ),
       filter( result => result.count>20 )
     );
  }

next, without map and I always get all records.

Any ideas?

---------CORRECT CODE------------

getVotes2(): Observable<Vote[]> {
 return this._http.get<Vote[]>(url)
  .pipe(
    map( results => results.filter( r => r.count < 20) )
  )
}
like image 297
3D_fun Avatar asked Aug 17 '18 14:08

3D_fun


1 Answers

You're confused on the use of the rx filter operator.

The filter rx operator is NOT the same as the array filter operator. The rx filter operates on a stream and excludes things from THE STREAM that meet a condition, the array filter operator operates on an array and removes items from an array based on a condition.

What you're currently doing is filtering the stream on some undefined "count" property of the array itself, so you're saying "if undefined > 20, then don't let the item through the stream", and one of the quirks of javascript, undefined is not greater than 20 despite being an invalid comparison.

What you need to do is this:

getVotes2(): Observable<Vote[]> {
 return this._http.get<Vote[]>(url)
  .pipe(
    map( results => results.filter(r => r.count > 20) )
  );
}

This way, you use rx Map to perform an operation on the item IN the stream and use the array filter on the item to filter the array.

Edit: as pointed out, the typing also needs to be correct to let typescript know that you're expecting an array of vote objects rather than a single vote object.

like image 112
bryan60 Avatar answered Nov 09 '22 11:11

bryan60