Js: Filter Object Array For Partial Matches
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
Solution 1:
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 = newRegExp(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()))
Solution 2:
Since you are using ES6, use the includes
method to test for the substring.
arr.filter(x => x.title.includes(searchStr));
Solution 3:
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;
}
Post a Comment for "Js: Filter Object Array For Partial Matches"