-1

I am learning RxJS library, I am getting array of object from backend, I want to filter it using RxJS.

I tried this:

.pipe(
        map(dataArray => from(dataArray).pipe(
          map(dataObject => {
            filter(dataObject.Code === 'ABC' || dataObject.Code === 'XYZ')
          }
        ))
      )

but it is not working, getting lots of syntax error

  • Did you look at this? https://stackoverflow.com/questions/37991713/simple-filter-on-array-of-rxjs-observable – misha130 Jul 08 '21 at 07:34

2 Answers2

1

RxJS filter operator is != Javascript's Array#filter function.

The former is used to filter out emissions from the observable based on a condition.

To filter out specific elements of an array, you'd need to use JS Array#filter. But you were right initially to go with the map operator to transform the incoming emission.

Try the following

someObservable$.pipe(
  map((dataArray: any[]) => 
    dataArray.filter((dataObject: any) => 
      dataObject.Code === 'ABC' || dataObject.Code === 'XYZ'
    )
  )
).subscribe(
  ...
);
ruth
  • 29,535
  • 4
  • 30
  • 57
  • It worked for me, but just asking, my response is in Array of object, and as i learned about filter, filter takes input stream of observable, then how filter will work without converting array of object into Observable stream? –  Jul 08 '21 at 07:37
  • Again, the filtering you're asking about is filtering a stream of emissions from an observable. Eg. if the `someObservable$` in the post emits every 5 seconds, and you wish to get only the emissions that pass some criteria, then you'd use the RxJS `filter` pipe. The filtering that you actually need in your context is to filter a specific array. Then you'd go with JS array filtering methods. There is no need for RxJS there. – ruth Jul 08 '21 at 07:46
0

Update the response is error: filter is to filter the whole object, not to filter an array

to complementary, the filter rxjs is
from(dataArray).pipe(
  filter(dataObject=>dataObject.Code === 'ABC' || dataObject.Code === 'XYZ')
)

NOTE, In your code you use pipe map pipe map... you can use pipe(rxjsoperator1,rxjsoperator2,rxjsoperator3,...)

some like:

.pipe(
   map(dataArray => from(dataArray),
   map(dataObject=>....),
   tap(res=>{console.log(res)}),
   filter(dataObject=>dataObject.Code === 'ABC' || dataObject.Code === 'XYZ')
  )
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • 1
    @techguy ::glups:: your'e correct, filter is to filter the whole object, not to filter an array,e.e. we subscribe to navigation.events and only wnat the navigation.start like this SO:https://stackoverflow.com/questions/50353164/angular-6-router-events-filter-filter-does-not-exist-on-type-observableevent, sorry for the confusion – Eliseo Jul 08 '21 at 09:18