How to use _.where () in underscore to compare values ​​regardless of case

I have a webpage where, if something is printed in the search field, it iterates through the file for this value, so I need the search / search to be case insensitive. Case sensitivity should remain in the file, but this is not case-sensitive for comparison purposes. so I am currently using the underscore command:

arr=_.where(arr,filter); 

but 2 arr and filter arrays - I need to compare / use them regardless of the case, so the final result of arr contains results that will display upper and lower case, but correspond to the values ​​in arr . can someone help?

+6
source share
2 answers

Unfortunately, JS is small when it comes to internationalized case-insensitive string comparisons. If you just stick to ASCII, the solution is pretty simple (using filter , but not where ):

 function getMatches(query, arr) { var lowerQuery = query.toLowerCase(); return _.filter(arr, function(term) { return term.toLowerCase() == lowerQuery; }); } 

Or if you want to pre-comprehend everything because you expect to make many requests in one JS session:

 var index = _.groupBy(arr, function(term) { return term.toLowerCase(); }); // Post-process index to reduce memory footprint by turning redundant values to nulls // (which take up less memory than arrays with a string in them). index = _.object(_.map(index, function(terms, key) { return [key, (terms.length == 1 && terms[0].toLowerCase() == terms[0] ? null : terms)]; })); function getMatches(query) { var lowerQuery = query.toLowerCase(); return (lowerQuery in index ? index[lowerQuery] || lowerQuery : []); } 

This second method has the advantage of only calculating toLowercase() minimum number of times and the minimum data storage due to the post-processing step.

Here's the JSFiddle for

+1
source

Try filter instead:

 var filter = ["Apple", "bANAna", "orange"]; var arr = ["apPle", "ORANGE"]; // make filter lower case once var filterLower = _.invoke(filter, "toLowerCase"); var arr2 = _.filter(arr, function(v) { // make entry lower case and see if it is in filterLower return _.contains(filterLower, v.toLowerCase()); }); console.dir(arr2); 
 <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script> 
+2
source

Source: https://habr.com/ru/post/980752/


All Articles