arrays – JavaScript equivalent of PHP function: array_flip

arrays – JavaScript equivalent of PHP function: array_flip

Dont think theres 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;
}

ES6 version

const example = { a: foo, b: bar };

const flipped = Object.entries(example)
  .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); 

// flipped is {foo: a, bar: b}

ES5 version

var example = {a: foo, b: bar}; 

var flipped = Object.keys(example)                //get the keys as an array
    .reduce(function(obj, key) {                  //build up new object
        obj[example[key]] = key;
        return obj;
    }, {});                                       //{} is the starting value of obj

// flipped is {foo: a, bar: b}

arrays – JavaScript equivalent of PHP function: array_flip

Using underscore _.invert

_.invert([1, 2]) 
//{1: 0, 2: 1}

_.invert({a: b, c: d}) 
//{b: a, d: c}

Leave a Reply

Your email address will not be published. Required fields are marked *