JuanmaPérez
JuanmaPérez

Reputation: 79

Filter Observable array according to an if condition

I receive a stream of elements from a get call to an API and in the first time I do this I don't need to filter this data. I can present the information as it comes.

But I have a form an according to the filters that someone could select, I need to filter the data.

The main problem that I have is I am iterating over all elements in the array with a map operator and returning this country when it has the same continent as the filter.continent but when it doesn't match it returns undefined.

Then after pass by this filter I obtain something like this:

[undefined, {some country data}, undefined, undefined, {some country data}]

This is my example of code for this refilter function

refilterValues(){
    Observable.from(this.data)
    .map((country)=>{
      if(this.filters.continent == "All"){
        return country;
      }else{
        if(country["continent"] == this.filters.continent){
          console.log(country)

          return country
        }
      }
    })
}

Upvotes: 2

Views: 3857

Answers (1)

Pedro Arantes
Pedro Arantes

Reputation: 5379

You should use filter operator instead of map operator. Map iterates over all elements and returns something, even if your logic returns nothing (because of that appears the undefined in your array). Filter takes the observable output and ONLY returns it if your logic returns true.

Filter items emitted by the source Observable by only emitting those that satisfy a specified predicate.

refilterValues(){
  Observable.from(this.data)
    .filter((country)=>{
      if(this.filters.continent == "All"){
        return true;
      }else{
        if(country["continent"] == this.filters.continent){
         console.log(country)

        return true
      }
      return false
    }
  })
}

Upvotes: 2

Related Questions