views:

144

answers:

1

Is there any shortcut to accomplishing the equivalent of PHP's array_flip in javascript or does it have to be done via brute force looping?

It has to be used for dozens of arrays so even small speedups will probably add up.

+5  A: 

Don't think there's one built in. Example implementation here, though :).

function array_flip( trans )
{
    var key, tmp_ar = {};

    for ( key in trans )
    {
        if ( trans.hasOwnProperty( key ) )
        {
            tmp_ar[trans[key]] = key;
        }
    }

    return tmp_ar;
}
pianoman
@pianoman - I added the hasOwnProperty check. Hope you don't mind =)
Peter Bailey
I wouldn't recommend phpjs.org: the code quality is underwhelming and some functions don't work in IE at all! If you want to program in JS, learn it!
Christoph
also keep in mind that this only works reliably if the property values have a unique string representation
Christoph
@Peter Bailey No minding at all; thanks!
pianoman
@Christoph - See your point, but if the properties aren't unique, one really shouldn't be flipping the array to begin with ಠ_ಠ
pianoman