Avg. Rating 1.0

Problem

If you have two ActionScript Arrays and you want to merge them together into one Array containing the contents of both of them the first thing that comes to peoples mind on how to do this is they loop over all of the items in one of the Arrays and push the items into the other Array.

Solution

Looping over all of the items is not very elegant. By using the built in apply method that is on every Function in ActionScript you can do the same thing with out the need to loop over anything. The apply method takes two arguments, the scope which we can pass null and an Array of arguments that is going to be injected into your method. In this case we want to use the push method on Array.

Detailed explanation

This will add all of the items from array2 into array1.

package
{
    public class ArrayUtils
    {   
        public static function merge( array1:Array, array2:Array
):Array
        {
            return array1.push.apply( null, array2 );
        }
    }
}

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes