actionscript-3array-flip

equivalent of php's array_flip in flash actionscript 3?


Is there an equivalent of php's array_flip() in flash actionscript 3? Here's the definition for array_flip:

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

If not, what is the least verbose and most efficient way to achieve the same results as array_flip() in actionscript 3?


Solution

  • Use this function:

    function flip(obj:Object):Object
    {
        var base:Object = {};
    
        for(var i:String in obj)
        {
            base[obj[i]] = i;
        }
    
        return base;
    }
    

    Demo:

    var array:Array = [];
    
    array["a"] = "a1";
    array["b"] = "b2";
    array["c"] = "c3";
    
    var newObj:Object = flip(array);
    
    trace(newObj.b2); // b