sharf
sharf

Reputation: 2143

Filtering large list with javascript

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

Currently I'm 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 be manageable with that code.

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

Upvotes: 6

Views: 2661

Answers (1)

marianc
marianc

Reputation: 449

I think there are many possible ways to optimize the search but whether you decide to use the code as shown in the question or use ajax calls I would suggest as an improvement to reduce the number of calls to the search function by using throttle / debounce. This will prevent the search to be called after each key stroke but instead will delay search execution with a number of milliseconds after the last key stroke. For example the code above 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 debounce function over the net, but in the above example I have used jquery-debounced. In order to see how this works please check this jsfiddle. Another implementation is available in underscore.js library. Also I found a nice article on this subject.

Upvotes: 5

Related Questions