I have a user input that may include a street, postal code, city, or a combination of them. How can I filter an array of objects to find those that contain any of these strings in the corresponding fields?
getFilteredCentersSuggestions(searchTerm: string) {
searchTerm = searchTerm.toLowerCase();
return this.centersList.filter((center) => center.city.toLowerCase().includes(searchTerm) || center.postalCode.toLowerCase().includes(searchTerm) || center.street.toLowerCase().includes(searchTerm));
}
The current code works well for single terms, but when entering multiple terms like "city postalCode", it fails to return the desired results...
Is there a way to directly filter the object fields or do I need to split the input and apply additional filtering within the existing 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