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

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


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.


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.


I wouldn't worry too much about performance in this case. A desktop computer should eat up 1000, or 10,000 evaluations without sweat. I would avoid any kind of complex optimisation because the risk of breaking functionality is probably higher than the benefit of slightly efficient processing.

Javascript (ECMAScript 5) does provide new methods for filtering arrays. As a native method it is supposed to be a little faster.

var regex = ...results = json.filter(function(result) {   return regex.test(result.name)}

Array.prototype.filter is supported in modern browsers, see http://kangax.github.com/es5-compat-table/.A patch for older browsers is can be added with this: https://github.com/kriskowal/es5-shim