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.
To our surprise, for-loops are much faster than the Array. filter method. To be precise, the Filter method is 77% slower than for loop.
The filters key allows you to filter the query results for records matching specific values. You can string together multiple filters by constructing JSON arrays called filters, separating each filter by a comma, and joining them by the AND or the OR operator.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.
From experience, the following algorithm works quite well:
When the user types the first letter, you perform a search using Array.filter()
perhaps and store that result under whatever the user types (e.g. "j");
When the user types another letter (e.g. "o"), you perform the search on whatever was typed before ("j"), reducing the number of items to go through
When the user deletes one or more characters you try to find the stored searches based on whatever is left in the search box; if all fails, you show an empty list and invalidate the previously stored searches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With