admin管理员组

文章数量:1325236

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!

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!

Share Improve this question asked Mar 28, 2017 at 11:56 traptrap 2,6407 gold badges27 silver badges45 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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()});

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;
}

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'));

本文标签: javascriptLodash filter ignore caseStack Overflow