Filtering a large list using javascript

I have a very large list of elements (14000+), I want to have a search field that, when entering text into it, filters the results and hides unrelated elements.

I am currently using this:

$.expr[':'].containsIgnoreCase = function (n, i, m) { return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; }; $("#search").on("keyup", function () { var filter = $("#search").val(); $(".list-group-item").not(":containsIgnoreCase('" + filter + "')").addClass("hidden"); $(".list-group-item:containsIgnoreCase('" + filter + "')").removeClass("hidden"); }); 

Which works wonderfully ... on smaller lists. This list is simply too large to manage this code.

I do not know if there is any other code that can handle this client side of many elements. If not, would it be better to leave this list empty and execute an ajax request to populate the list as matches are made?

+5
source share
1 answer

I think there are many possible ways to optimize your search, but do you decide to use the code as shown in the question, or use ajax calls, which I would suggest as an improvement to reduce the number of calls to the search function using the / debounce choke. This will prevent the call from being searched after each key press, but instead will delay the search with the number of milliseconds since the last key press. For example, the above code can be changed as follows:

 function searchFunction () { var filter = $("#search").val(); $(".list-group-item").not(":containsIgnoreCase('" + filter + "')").addClass("hidden"); $(".list-group-item:containsIgnoreCase('" + filter + "')").removeClass("hidden"); } $("#search").on("keyup", $.debounce(searchFunction, 300)); 

There are many open source implementations of the debounce function over the network, but in the example above, I used jquery-debounced . To see how this works, please check jsfiddle . Another implementation is available in the underscore.js library . I also found a good article on this topic.

+2
source

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


All Articles