Reputation: 17342
Is it possible to filter for those objects, which matches for a search string?
const arr = [
{ title: 'Just an example' },
{ title: 'Another exam'},
{ title: 'Something different'}
]
I tried this
arr.filter(x => { return x.title === searchStr });
But this will filter only exact matches, but I need to find all partial matches. let searchStr = 'exam'
should give me two objects (first and second), let searchStr = 'examp'
should give me only one object as the result.
Upvotes: 9
Views: 23764
Reputation: 278
You can check with the indexOf and also add toLowerCase() method to increase the possibility of a match
myArr.filter(function(x) {
return x.title.toLowerCase().indexOf(searchString.toLowerCase()) > -1;
}
Upvotes: 0
Reputation: 4319
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.
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))
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()))
Upvotes: 33