Search code examples
arraysactionscript-3merging-data

AS3 Fastest way to merge multiple arrays


I'm trying to write a function where I can specify any amount of array, and the return value will be an array containing the contents of all of the specified arrays.

I've done this, but it seems like a really slow and ugly way of doing it:

var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];


function merge(...multi):Array
{
    var out:String = "";

    for each(var i:Array in multi)
    {
        out += i.join(',');
    }

    return out.split(',');
}

trace(merge(ar1, ar2));

Is there an inbuilt and more efficient / nice way of achieving this? The result does not need to be in the same order as the input - completely unsorted is fine.


Solution

  • You can use concat.

    If the parameters specify an array, the elements of that array are concatenated.

    var ar1:Array = [1,2,3,4,5,6,7,8,9];
    var ar2:Array = ['a','b','c','d','e','f','g','h'];
    var ar3:Array = ['i','j','k','l'];
    
    var ar4 = ar1.concat(ar2, ar3); // or: ar1.concat(ar2).concat(ar3);
    

    To make a single array out of a 2 dimensional array you can use this function:

    private function flatten(arrays:Array):Array {
        var result:Array = [];
        for(var i:int=0;i<arrays.length;i++){
            result = result.concat(arrays[i]);
        }
        return result;
    }
    
    // call
    var ar4 = [ar1, ar2, ar3];
    var ar5 = flatten(ar4);
    

    You can also use varargs to merge multiple arrays:

    private function merge(...arrays):Array {
        var result:Array = [];
        for(var i:int=0;i<arrays.length;i++){
            result = result.concat(arrays[i]);
        }
        return result;
    }
    
    // call
    var ar5 = merge(ar1, ar2, ar3);