javascriptangularmultiple-conditionspipes-filters

Shorter condition in the filter pipe


I have a pipe, that filter dates of clients. Now it looks like:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(clients: any[], searchText: string): any[] {
    if(!clients) return [];
    if(!searchText) return clients;

    searchText = searchText.toLowerCase();
    return clients.filter( it => {
      if (it.firstName.toLowerCase().includes(searchText)) {
        return it.firstName.toLowerCase().includes(searchText);
      }
      if (it.lastName.toLowerCase().includes(searchText)) {
        return it.lastName.toLowerCase().includes(searchText);
      }
      if (it.street.toLowerCase().includes(searchText)) {
        return it.street.toLowerCase().includes(searchText);
      }
      if (it.city.toLowerCase().includes(searchText)) {
        return it.city.toLowerCase().includes(searchText);
      }
      if (it.zipCode.toLowerCase().includes(searchText)) {
        return it.zipCode.toLowerCase().includes(searchText);
      }
      if (it.country.toLowerCase().includes(searchText)) {
        return it.country.toLowerCase().includes(searchText);
      }
      if (it.email.toLowerCase().includes(searchText)) {
        return it.email.toLowerCase().includes(searchText);
      }
      if (it.phone.toLowerCase().includes(searchText)) {
        return it.phone.toLowerCase().includes(searchText);
      }
    });
  }
}

But I understend, that the condition can be written shorter. Please, tell me, how can I do it?..


Solution

  • Here is a shorter way to write the condition:

    return clients.filter(it => 
        it.firstName.toLowerCase().includes(searchText) ||
        it.lastName.toLowerCase().includes(searchText) ||
        it.street.toLowerCase().includes(searchText) ||
        it.city.toLowerCase().includes(searchText) ||
        it.zipCode.toLowerCase().includes(searchText) ||
        it.country.toLowerCase().includes(searchText) ||
        it.email.toLowerCase().includes(searchText) ||
        it.phone.toLowerCase().includes(searchText)
    );