View Single Post
Nutrox's Avatar Nutrox Nutrox is offline Super Moderator 17 Creative Assets 2006-11-22 #34 Old  
031 - Array Mapping
Last edited by Nutrox : 2006-11-22 at 04:29.
 
Array mapping can come in very useful sometimes. What array mapping basically does is pass each array value to a function, and that function can then either alter the array value or return a result based on the array value.

I have included a prototype function and a standard function here just in case you prefer a particular flava.

You setup the Array prototype method like this:

ActionScript Code:
  1. Array.prototype.map = function(callback)
  2. {
  3.     var a = [];
  4.     var n = this.length;
  5.     while (n--)
  6.     {
  7.         a[n] = callback(this, n, this[n]);
  8.     }
  9.     return a;
  10. }

Prototype Example 1
This example checks to see which values in the myNumbers array are greater than 3. The results (in this example true or false) will be returned in an array.

ActionScript Code:
  1. var myNumbers = [1, 2, 3, 4, 5, 6];
  2. var results   = myNumbers.map(checkNumbers);
  3.  
  4. trace( results ); // false, false, false, true, true, true
  5.  
  6. //
  7.  
  8. function checkNumbers(array, index, value)
  9. {
  10.     // Check if the value is greater than 3.
  11.     return value > 3;
  12. }
Prototype Example 2
This example will prefix each value in the myNames array with "Name: ".

ActionScript Code:
  1. var myNames = ["Andy", "Bob", "Charlie", "Dood"];
  2. var newNames = myNames.map(changeNames);
  3.  
  4. trace( newNames ); // Name: Andy, Name: Bob, Name: Charlie, Name: Dood
  5.  
  6. //
  7.  
  8. function changeNames(array, index, value)
  9. {
  10.     return "Name: " + value;
  11. }
Better Example 1
We have left the world of prototypes now. This is the same example as Prototype Example 1 but instead of using a prototype a standalone function is used for the array mapping.

ActionScript Code:
  1. function mapArray(array:Array, callback:Function):Array
  2. {
  3.     var a:Array = [];
  4.     var n:Number = array.length;
  5.     while (n--)
  6.     {
  7.         a[n] = callback(array, n, array[n]);
  8.     }
  9.     return a;
  10. }
  11.  
  12. //
  13.  
  14. var myNumbers:Array = [1, 2, 3, 4, 5, 6];
  15. var results:Array   = mapArray(myNumbers, checkNumbers);
  16.  
  17. trace( results ); // false, false, false, true, true, true
  18.  
  19. //
  20.  
  21. function checkNumbers(array:Array, index:Number, value):Array
  22. {
  23.     return value > 3;
  24. }


PS: Array mapping is built-in to the AS3 Array class, so these examples are only useful for AS1 / AS2.