Reputation: 2640
is there a way of case-insensitive filter with lodash? I tried this (see below), but this works only partly (when the user input is also lowercase). Another problem is here after one search all the characters are in lower case.
I want to filter regardless of how (lower case or upper).
filter(q: string) {
let query = q.trim();
let searchData = [];
searchData = clone(this.data);
searchData = searchData.map((entity) => {
entity.email = entity.email.toLowerCase();
return entity;
});
if (query) {
this.approverEntities = filter(searchData, (a) => a.email.indexOf(query) >= 0);
} else {
this.approverEntities = this.data;
}
}
thanks in advance!
Upvotes: 2
Views: 8372
Reputation: 335
This is how I did a case insensitive filter while also only requiring a substring:
this.approverEntities = filter(searchData, function(a){
return a.email.toLowerCase().indexOf((query).toLowerCase()) !== -1;
}
Upvotes: 2
Reputation: 31641
This approach worked out great for me:
this.approverEntities = _.filter(searchData, (a) => {return new RegExp(a.email, 'i').test(query)});
The one caveat is that if the a.email
contains any special characters the regex expression will process it as regex tokens (e.g. parenthesis, brackets, etc.). This solution will handle special characters regardless...
this.approverEntities = _.filter(searchData, (a) => {return a.email.toLowerCase() == query.toLowerCase()});
Upvotes: 3
Reputation: 11211
You can use filter(), method(), and a case-insensitive regular expression:
_.filter(searchData, _.method('email.match', /foo/i));
Or, if the search term is dynamic:
const filterCaseInsensitive = (search, searchData) =>
_.filter(searchData, _.method('email.match', new RegExp(search, 'i'));
Upvotes: 1