Ionic 3- filter list based on more than one field


#1

I’m iterating a list of jobs and there’s a search implemented on this list. Search is working but now it only filters list based on one field.

Here’s my list:

<ion-card *ngFor="let job of allJobs | search : searchTerm">
    <ion-grid>
    <ion-row>
        <ion-col>
        <div>
            <span> {{job.day | uppercase}}</span>
            <span> {{job.month | uppercase}}</span>
        </div>
        </ion-col>

        <ion-col>
        <div>
            <span>{{job.time}}</span>
            <span>{{job.name}}</span>
        </div>
        </ion-col>
    </ion-row>
    </ion-grid>
</ion-card>

I made a pipe for implementing search. Here’s the code for it.

  transform(items: any[], terms: string): any[] {
    if(!items) return [];
    if(!terms) return items;
    terms = terms.toLowerCase();
    return items.filter( it => {
      return it.name.toLowerCase().includes(terms); // only filter name
    });
  }

Now the list gets filtered only based on the name field. I wanna filter the list based on day , month and time as well.

Can anyone tell me how to make this happen? Thanks!


#2
  transform(items: any[], terms: string): any[] {
    if (!items) return [];
    if (!terms) return items;
    terms = terms.toLowerCase();
    terms = terms.trim();
    return items.filter(it => {
      if (it.day) {
        return it.day.toLowerCase().includes(terms);
      }
      if (it.month) {
        return it.month.toLowerCase().includes(terms);
      }
      if (it.time) {
        return it.time.toLowerCase().includes(terms);
      }
      if (it.name) {
        return it.name.toLowerCase().includes(terms);
      }
    });
  }

#3

I would consider this pipe abuse, and suggest doing this work in the controller instead.


#4

I would have to agree, pipes are expensive


#5

Can you show an example?