Barrie Reader
Barrie Reader

Reputation: 10715

Search a multitude of arrays

Hey, I am searching each array separately for specific inputs from a user.

if ($.inArray(i.val(), helloInputArray) > -1) { //IF HELLO
                    if (hello == 0) { //HAVE YOU ALREADY SAID HI?
                        r = Math.floor(Math.random()*4);                        
                        o.html(o.html()+helloOutputArray[r]);
                        hello = 1;
                        i.val('');
                    } else { //IF YOU'VE ALREADY SAID HI...
                        o.html(o.html()+'I already said hi to you!<br />');
                        i.val('');
                    }
                } else if ($.inArray(i.val(), byeInputArray) > -1) { //IF GOODBYE
                    if (bye == 0) {
                        r = Math.floor(Math.random()*4);                        
                        o.html(o.html()+byeOutputArray[r]);
                        i.val('');
                    } else {
                        o.html(o.html()+'I already said goodbye... Go away!');
                        i.val('');
                    }
                }

Is there any way I can just search all arrays at once, as I'm going to need to search each array for a string.

ahem

so - If I typed 'ae', then I want it to go through every item in every array and return ALL the strings with 'ae' in it.

^_^ <( bad wording... )

Upvotes: 1

Views: 74

Answers (1)

user113716
user113716

Reputation: 322452

If I'm understanding you correctly, you want to consolidate your separate arrays into one for the purpose of doing one loop, but you don't want to modify the original arrays.

If so, try this:

if( $.inArray( i.val(), helloInputArray.concat( byeOutputArray) ) > -1 ) {
    ...

The .concat() method will create a copy of the two Arrays joined together as one, so the originals are not modified. That copy is passed to the $.inArray() method as the second parameter.


EDIT:

From your comment below, it sounds like you want to test if i.val() is a substring of any items in the array.

If that's right, you probably won't use $.inArray, but rather will use $.each() to iterate of the Array, and test for the value.

var isInArray = false;
var value = i.val();

$.each( helloInputArray.concat(byeOutputArray), function(i,val) {
    if( val.indexOf( value ) > -1 ) {
        isInArray = true;
        return false;
    }
});

if ( isInArray ) > -1) { 
    if (hello == 0) { 
        r = Math.floor(Math.random()*4);                        
        o.html(o.html()+helloOutputArray[r]);
      ...

Upvotes: 2

Related Questions