Cleanly merge two arrays in ActionScript (3.0)?

mellis picture mellis · Dec 2, 2008 · Viewed 22.5k times · Source

What's a nice way to merge two sorted arrays in ActionScript (specifically ActionScript 3.0)? The resulting array should be sorted and without duplicates.

Answer

hasseg picture hasseg · Dec 3, 2008

To merge (concatenate) arrays, use .concat().

Below are two examples of how you can concatenate arrays and remove duplicates at the same time.

More convenient way: (you can use ArrayUtil.createUniqueCopy() from as3corelib)

// from as3corelib:
import com.adobe.utils.ArrayUtil;

var a1:Array = ["a", "b", "c"];
var a2:Array = ["c", "b", "x", "y"];

var c:Array = ArrayUtil.createUniqueCopy(a1.concat(a2)); // result: ["a", "b", "c", "x", "y"]

Slightly faster way: (you can loop through the arrays yourself and use Array.indexOf() to check for duplicates)

var a1:Array = ["a", "b", "c"];
var a2:Array = ["c", "b", "x", "y"];
var a3:Array = ["a", "x", "x", "y", "z"];

var c:Array = arrConcatUnique(a1, a2, a3); // result: ["a", "b", "c", "x", "y", "z"]

private function arrConcatUnique(...args):Array
{
    var retArr:Array = new Array();
    for each (var arg:* in args)
    {
        if (arg is Array)
        {
            for each (var value:* in arg)
            {
                if (retArr.indexOf(value) == -1)
                    retArr.push(value);
            }
        }
    }
    return retArr;
}