views:

30

answers:

1

Hello

var myarr= Array('test1','test2','test3');

var searchTerm = "test";
var rSearchTerm = new RegExp( searchTerm,'i');

$.each(myarr, function(i) {
        if (myarr[i].match(rSearchTerm)) {
            //item found
        }

    });​

guys is there any way to make my search algorithm better ? "myarr" will be a big array so i want to make sure that i'm using the best way to search in it

thanks alot

+2  A: 

I would recommend the flollowing (since jQuery provides this convenience):

$.each(myarr, function(index, value) {
    if (rSearchTerm.test(value)) {
        // item found
    }
});

The only other approach to make this faster is probably to do this without jQuery in a plain for-loop, since it does not involve callbacks:

for (var i = 0; i < myarr.length; i++) {
    if (rSearchTerm.test(myarr[i])) {
        // item found
    }
}

EDIT: I changed .match() to .test(), like Andy E suggested.

elusive
+1, the only change I would make is `rSearchTerm.test(myarr[i])` instead of using *match()*. Although it's a tiny optimization, *test()* is more appropriate for an *if* statement if you're not doing anything with the matched string.
Andy E
thank you guys, should i modify anything in my RegExp ?
From.ME.to.YOU
@Andy: Very good addition! This could lead to a major performance boost when using a large array.
elusive
@From.ME.to.YOU: One last problem might be the following: You have to pass a regular expression to search for. If you want the user to input something, this is merely what you need. There are faster ways to search for simple strings, if this is what you need.
elusive