views:

1660

answers:

3

I need to know how I can search an array for some literal text and have it used as a condition whether to continue.

Heres why: Each time I execute a function I am pushing the ID of the property it acts upon into an array. I need my funtion to check if that ID is in the array already and if it is, remove it and execute my other function (the opposite).

Heres an example array:

var myArray = new Array();
myArray.push([1.000,1.000,"test1"]);
myArray.push([2.000,2.000,"test2"]);
myArray.push([3.000,3.000,"test3"]);

I know the Grep function can search but I can't get it to evaluate true or false if it finds something.

Heres my ideal use of the search evaluation.

function searcher(id){
    if(myArray.grep(id);){
        oppositeFunction(id);
    }else{
        function(id);
    }
}
A: 
function arraytest(){
    var myArray = new Array();  
    myArray.push(["test1"]);  
    myArray.push(["test2"]);  
    myArray.push(["test3"]);  
    for(i=0;i<myArray.length;i++){
     if(myArray[i]=="test1"){
      successFunction("Celebration\!");
     }
    }
}

Is an iterative loop that will search the first object in each array element, but it won't search nested elements such as in my demo Array

Supernovah
+3  A: 

Grep isn't a standard javascript Array method. Are you using a javascript library that has added this method to Array? If so, you may want to look at its implementation. Since you are pushing arrays into the array, it would need to be able to search the elements of each element of the array, instead of the array itself for the id. A function to do what you want would be:

 function superContains(aray,id)
 {
      var contains = false;
      for (var i=0, len = aray.length; !contains && i < len; ++i)
      {
           var elem = aray[i];
            if (elem.constructor && elem.constructor == Array)
            {
                 contains = superContains(elem,id);
            }
            else
            {
                 contains = elem == id;   //  or elem.match(id)
            }
      }
      return contains;
 }
tvanfosson
I thought typeof would work, but apparently typeof(elem) is undefined if elem is an array.
tvanfosson
alert(typeof [] ); // alerts object
some
+3  A: 

Looks like you want to use an hash-mapp instead:

var myhash = {};

myhash["test1"] = [1.000,1.000];
myhash["test2"] = [2.000,2.000];
myhash["test3"] = [3.000,3.000];

function searcher(id){
  if (myhash[id]) {
        delete myhash[id];
        oppositeFunction(id);
    }else{
        normalFunction(id);
    }
}
some