views:

4709

answers:

2

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.

+11  A: 

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;
}
hasseg
He asked for a 'nice' way... :)
Luke
Ok, maybe the other way I added into the answer could be considered 'nicer'
hasseg
Thanks, worked like a charm.
John Ballinger
+2  A: 

This is kind of an simple algorithm to write. I would be surprised if there were a more direct way to do this in Actionscript.

function merge(a1:Array, a2:Array):Array {
    var result:Array = [];
    var i1:int = 0, i2:int = 0;

    while (i1 < a1.length && i2 < a2.length) {
        if (a1[i1] < a2[i2]) {
            result.push(a1[i1]);
            i1++;
        } else if (a2[i2] < a1[i1]) {
            result.push(a2[i2]);
            i2++;
        } else {
            result.push(a1[i1]);
            i1++;
            i2++;
        }
    }

    while (i1 < a1.length) result.push(a1[i1++]);
    while (i2 < a2.length) result.push(a2[i2++]);

    return result;
}
Tmdean