Query Array Prototype

I recently found myself in need of a method to search values in a multidimensional array. I searched around a bit and could only find methods that searched the entire array for a specific value. This doesn’t work for me, however, because a particular value may appear in several places within my array. I needed a way to look for a value in a specific positional within the array, so I ended up creating the following prototype:

Array.prototype.queryArray = function(columnName:String,columnValue:String):Number {
 var arrLength:Number = this.length;
 while(arrLength–) {
  if(this[arrLength][columnName] == columnValue){
   return arrLength;
  };
 };
 return -1;
};

In order to use the solution I came up with, you also have to create your array the way I do. I assign a name to each element within each ‘record’ which turns it into a table of sorts. For example:

var my_array:Array = new Array();
my_array.push({firstname:”joe”,lastname:”shmoe”,phone:”5558118″});
my_array.push({firstname:”jane”,lastname:”doe”,phone:”5558888″});

The prototype looks for a column name and a value to search for within that column. If a match is found the array index is returned. If no match is found, -1 is returned. Need some examples?

var searchResult:Number = my_array.queryArray(“phone”,”5558888″);
trace(searchResult); //returns 1

searchResult = my_array.queryArray(“firstname”,”joe”);
trace(searchResult); //returns 0

searchResult = my_array.queryArray(“firstname”,”sally”);
trace(searchResult); //returns -1

Using this prototype I can check to see if a ‘record’ exists for a particular object. If it exists, I can update that record with new values or delete it from the array. If it doesn’t exist, I can push it.

-rG