Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter id string contains substring

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading