I have address options and Autocomplete field which users can filter and find their address. For example these are the addresses
[
{
"id": "af332e9d205ca",
"label": "500 S Himes Ave Apt 2 Tampa, FL 33609",
"data": {
"zip": "33609",
"city": "Tampa",
"state": "FL",
"streetAddress": "500 S Himes Ave",
"secondaryAddress": "Apt 2"
}
},
{
"id": "53ffcb3f03da6",
"label": "500 S Himes Ave Apt 20 Tampa, FL 33609",
"data": {
"zip": "33609",
"city": "Tampa",
"state": "FL",
"streetAddress": "500 S Himes Ave",
"secondaryAddress": "Apt 20"
}
},
{
"id": "072cd5f7c09c4",
"label": "500 S Himes Ave Apt 21 Tampa, FL 33609",
"data": {
"zip": "33609",
"city": "Tampa",
"state": "FL",
"streetAddress": "500 S Himes Ave",
"secondaryAddress": "Apt 21"
}
},
{
"id": "c0fce5285fa31",
"label": "500 S Himes Ave Apt 22 Tampa, FL 33609",
"data": {
"zip": "33609",
"city": "Tampa",
"state": "FL",
"streetAddress": "500 S Himes Ave",
"secondaryAddress": "Apt 22"
}
},
{
"id": "306f91ef7f85d",
"label": "500 S Himes Ave Apt 23 Tampa, FL 33609",
"data": {
"zip": "33609",
"city": "Tampa",
"state": "FL",
"streetAddress": "500 S Himes Ave",
"secondaryAddress": "Apt 23"
}
},
]
This is the filtering function
const filterOptions = useCallback((options: IOption[], state) => {
const newOptions: IOption[] = [];
options.forEach((element) => {
if (element.label.toLowerCase().includes(state.inputValue.toLowerCase())) {
newOptions.push(element);
}
});
return newOptions;
}, []);
I am filtering against the label of each address object.
Let's take this one 500 S Himes Ave Apt 2 Tampa, FL 33609
.
500 S Himes Ave Apt 2
- works fine
500 S Himes Ave 2
- Doesn't work as String.prototype.includes
just checks the substring with an order from the position
( 0 if not mentioned ) and in this case it will return false
.
What is the better alternative for these cases where the user can input the text in arbitrary order?