I have implemented an autocomplete input that searches for project properties while typing. I am looking to enhance the existing code for better performance.
filterProjects(value: string) {
return this.projects.filter(
project =>
project.key.toLowerCase().indexOf(value.toLowerCase().trim()) >=
0 ||
project.name.toLowerCase().indexOf(value.toLowerCase().trim()) >=
0 ||
project.description?.toLowerCase().indexOf(value.toLowerCase().trim()) >=
0
);
}
and replacing it with the following code:
filterProjects(value: string) {
return this.projects.filter(project =>
[project.key, project.name, project.description].map(
str => str?.toLowerCase().indexOf(value.toLowerCase().trim()) >= 0
)
);
}
I decided to use optional chaining because the description
field can sometimes be null or undefined.
However, I am facing an issue where the function returns the array unmodified. Additionally, when the value is found in the description of one item, the array is not filtered to just that specific item.
Is there a solution apart from resorting to traditional checks like if (str !== undefined)
? Let me know your thoughts.