Home > Back-end >  How to filter id string contains substring
How to filter id string contains substring

Time:12-06

I have an input that could be a street, a postal code, a city or a combination on them. I want to filter an array of objects that includes any of this strings in these fields.

getFilterCentersSuggestions(term: string) {
    term = term.toLowerCase();
    return this.listOfCenters.filter((c) => c.city.toLowerCase().includes(term) || c.postalCode.toLowerCase().includes(term) || c.street.toLowerCase().includes(term));
  }

This code works if the input is only of one term, but if for example the input is "city postalCode", it doesnt't work...

Is there any way to filter directly the object fields or I have to split the input and make a filter inside the filter?

Example:

array:

[
  {
    id: "1",
    city: "city1",
    street: "street1",
    postalCode: "postalCode1"
  },
  {
    id: "2",
    city: "city1",
    street: "street2",
    postalCode: "postalCode2"
  },
  {
    id: "3",
    city: "city2",
    street: "street3",
    postalCode: "postalCode3"
  },
]

input 1: "city1 postalCode1"

expected result 1: object with id == 1


input 2: "city1"

expected result 1: objects with id == 1 && id == 2

CodePudding user response:

getFilterCentersSuggestions(termsString: string) {
  const terms = termsString.toLowerCase().split(' ')
  return this.listOfCenters.filter(c=>terms.every(term=>
    [c.city, c.postalCode, c.province].some(f=>f.toLowerCase().includes(term))))
}
  • Related