JS: Filter object array for partial matches
From your question I will assume you also want to match both uppercase and lowercase versions of your string, so here RegExps are the right (but not the only) choice.
RegExp solution:
First, define a case-insensitive RegExp with the i
flag, outside of the loop (this avoids re-creating a new RegExp instance on each iteration):
const regexp = new RegExp(searchStr, 'i');
Then you can filter the list with RegExp#test (String#match would work too):
arr.filter(x => regexp.test(x.title))
String#includes solution:
You could also use the .includes
method of String
, converting both strings to lowercase before comparing them:
arr.filter(x => x.title.toLowerCase().includes(searchStr.toLowerCase()))
Since you are using ES6, use the includes
method to test for the substring.
arr.filter(x => x.title.includes(searchStr));