Skip to content Skip to sidebar Skip to footer

Javascript / Jquery Faster Alternative To $.inarray When Pattern Matching Strings

I've got a large array of words in Javascript (~100,000), and I'd like to be able to quickly return a subset of them based on a text pattern. For example, I'd like to return all th

Solution 1:

If you just want to search for prefixes there are data structures just for that, such as the Trie and Ternary search trees

A quick Google search and some promissing Javascrit Trie and autocomplete implementations show up:

http://ejohn.org/blog/javascript-trie-performance-analysis/

Autocomplete using a trie

http://odhyan.com/blog/2010/11/trie-implementation-in-javascript/

Solution 2:

I have absolutely no idea if this is any faster (a jsperf test is probably in order...), but you can do it with one giant string and a RegExp search instead of arrays:

var giantStringOfWords = giantArrayOfWords.join(' ');
functionsearchForBeginning(beginning, str) {
    var pattern = newRegExp('\\b' + str + '\\w*'),
        matches = str.match(pattern);
    return matches;
}

var hapResults = searchForBeginning('hap', giantStringOfWords);

Solution 3:

The best approach is to structure the data better. Make an object with keys like "hap". That member holds an array of words (or word suffixes if you want to save space) or a separated string of words for regexp searching.

This means you will have shorter objects to iterate/search. Another way is to sort the arrays and use a binary search pattern. There's a good conversation about techniques and optimizations here: http://ejohn.org/blog/revised-javascript-dictionary-search/

Solution 4:

I suppose that using raw javascript can help a bit, you can do:

var arr = ["happy", "happiness", "nothere", "notHereEither", "happening"], subset = [];
for(var i = 0, len = arr.length; i < len; i ++) {
     if(arr[i].search("hap") !== -1) {
           subset.push(arr[i]);
     }
}
//subset === ["happy", "happiness","happening"]

Also, if the array is ordered you could break early if the first letter is bigger than the first of your search, instead of looping the entire array.

Solution 5:

var data = ['foo', 'happy', 'happiness', 'foohap'];    
jQuery.each(data, function(i, item) {
      if(item.match(/^hap/))
        console.log(item) 
    });

If you have the data in an array, you're going to have to loop through the whole thing.

Post a Comment for "Javascript / Jquery Faster Alternative To $.inarray When Pattern Matching Strings"