Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  189] [ 4]  / answers: 1 / hits: 39214  / 12 Years ago, mon, november 26, 2012, 12:00:00

Let's assume I have a huge (1000+) list of objects like this:



[{name: 'john dow', age: 38, gender:'m'}, {name: 'jane dow', age: 18, gender:'f'}, ..]


I want to filter this list by name (character wise).



filter('j') => [{name: 'john dow', age: 38, gender:'m'}, {name: 'jane dow', age: 18, gender:'f'}, ..]

filter('jo') => [{name: 'john dow', age: 38, gender:'m'}, ..]

filter('dow') => [{name: 'john dow', age: 38, gender:'m'}, {name: 'jane dow', age: 18, gender:'f'}, ..]


What is the highest performance way to do that? RegEx is obviously one of the keys, ordering the list beforehand if you assume that user usually tend to start names from the beginning may also a good idea, but it only helps in some cases.



Are there any JavaScript built-in functions for mapping a filter? I'd expect those to be faster than JavaScript implementations.



P.S.: Yes I want to filter on client side because of offline capabilities I want to offer.


More From » performance

 Answers
16

Although a substring index (such as a Suffix tree) would make this faster, the direct search would be:



function (s, l) {
return l.filter(function (v) {
return v.name.find(s) !== -1;
});
}


where s is the query string and l is the list of objects.


[#81797] Saturday, November 24, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samara

Total Points: 326
Total Questions: 106
Total Answers: 103

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
;