4 Replies Latest reply on Jun 30, 2006 10:17 AM by DavidBPrice

    Searching through an array

    ekokurtz Level 1
      To build an array of unique values, I want to check for each value using indexOf before doing a push if needed. I've seen examples of using this function in a simple array, but have not had luck trying any combination that finds the value, even though I know it's there:

      var checkValue = classArray.className.indexOf("Class 1");
      Alert.show(checkValue);
      if (checkValue === -1) {//add value - not found
      classArray.push({className:"Class "+censusArray[temp].sclass,data:censusArray[temp].sclass});
      }

      what is the syntax if the value you are looking for is in an actual array named pair, instead of just

      classArray..indexOf("Class 1"); ?

      All I have been able to get is a response of -1 (not found) or a run time errror - compiles just fine

      Ethan
        • 1. Re: Searching through an array
          ur_dtrain Level 1
          This works on simple arrays. If your array is an array of objects, you'll have to build an object that has identical properties for the comparison:

          var myObj:Object = new Object();
          myObj.className="Class 1";
          myObj.instructor="Bob";
          etc... (whatever your other properties are)

          Then:
          var checkVale = classArray.indexOf(myObj);
          • 2. Re: Searching through an array
            ekokurtz Level 1
            yeah, I tried that but it didn't work - checkValue still is coming back as -1

            var tempObj:Object = new Object(); tempObj.className = classArray .className; tempObj.data = classArray.data; var checkValue = classArray.indexOf(tempObj); Alert.show(checkValue); Alert.show(tempObj.className);
            • 3. Re: Searching through an array
              ntsiii Level 3
              Could you use an "associative array" (Object). If you do not need to keep the order of the elements, this is the easiest. It lis like a hash table.

              You might also look at ArrayCollection.

              Tracy
              • 4. Re: Searching through an array
                DavidBPrice Level 1
                I don't believe that approach will work for your array of objects as the array holds references to the objects so the indexOf will be comparing the reference not the value of the referenced object. If the associate array approache won't work in your situation you could do something like:
                var obj:Object = null;
                var found:Boolean = false;
                for each(obj in classArray)
                {
                if (obj.className == "class1")
                {
                found = true;
                break;
                }
                }
                if(found == false){push...