View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-05 #10 Old  
009 - Array item lookup/removal
 
If you have an indexed array (array with 1, 2, 3, 4, ... indexes) and you want to know the index of a certain object, you can use the following function:

ActionScript Code:
  1. // returns index of an item in array, -1 if it isn't in the array
  2.     function inArray(array:Array, item:Object):Number {
  3.         for (var i in array) {
  4.             if (array[i] == item) {
  5.                 return Number(i);
  6.             }
  7.         }
  8.         return -1;
  9.     }
If you want to remove a certain object from an array and want to know whether the object was found (and so removed) you can use the following method in conjunction with the previous one:

ActionScript Code:
  1. // tries to remove an item from array and returns whether it worked
  2.     function arrayRemove(array:Array, item:Object):Boolean {
  3.         var index:Number = inArray(array, item);
  4.         if (index != -1) {
  5.             array.splice(index, 1);
  6.         }
  7.         return index != -1;
  8.     }
Usage:

ActionScript Code:
  1. var names:Array = new Array("Bob", "Shirley", "Pete");
  2. trace(arrayRemove(array, "Bob")); // traces "true"
  3. trace(arrayRemove(array, "Bill")); // traces "false"
  4.  
---
You could also add these function to the Array class with prototyping as Nutrox explained in Tip 006. Or, you can add these methods to a global util class as explained in Tip 010