Jump to content

Searching in an Array?


Liquid Fire

Recommended Posts

I'd just add a couple of comments:

 

1) If you do build a function to do this, be sure to "break" out of the loop whne you find the value to prevent unnecessary execution.

 

2) You can also do this without looping through the array with a little slight of hand. However, it may or may not be more efficient based upon the size of the array. You would also want to use delimiters that would not appear in the data.:

 

(array is the array to be searched)

function in_array(searchArray, searchString)
{
    var array_to_string = '~' + searchArray.join('~') = '~';
    return ( (array_to_string.search(searchString)!=-1) ? true : false);
}

 

 

Link to comment
Share on other sites

I'd just add a couple of comments:

 

1) If you do build a function to do this, be sure to "break" out of the loop whne you find the value to prevent unnecessary execution.

 

2) You can also do this without looping through the array with a little slight of hand. However, it may or may not be more efficient based upon the size of the array. You would also want to use delimiters that would not appear in the data.:

 

(array is the array to be searched)

function in_array(searchArray, searchString)
{
    var array_to_string = '~' + searchArray.join('~') = '~';
    return ( (array_to_string.search(searchString)!=-1) ? true : false);
}

 

you will also want to add '~' to the beginning and end of your search string

Link to comment
Share on other sites

you will also want to add '~' to the beginning and end of your search string

 

Yes, I forgot to add that (I also used a '=' instead of '+' when creating the array_to_string to add it at then end of that) - thanks.

 

Fixed:

function in_array(searchArray, searchString)
{
    var array_to_string = '~' + searchArray.join('~') + '~';
    return ( (array_to_string.search('~'+searchString+'~')!=-1) ? true : false);
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.