-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

1

2 Answers 2

2

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(
  ...
);
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
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')
  )

1 Comment

@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:stackoverflow.com/questions/50353164/…, sorry for the confusion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.