Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the highest performance way to filter a list of JSON objects in JavaScript?

Tags:

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.

like image 963
wzr1337 Avatar asked Nov 26 '12 13:11

wzr1337


People also ask

Which is faster filter or for loop JavaScript?

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.

Can I filter JSON?

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.

Can I filter an array of objects JavaScript?

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.

How do you filter objects in JavaScript?

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.


1 Answers

From experience, the following algorithm works quite well:

  1. 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");

  2. 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

  3. 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.

like image 83
Ja͢ck Avatar answered Oct 22 '22 11:10

Ja͢ck