ck_
ck_

Reputation: 3403

JavaScript equivalent of PHP function: array_flip

Is there any shortcut to accomplishing the equivalent of PHP's array_flip function 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.

Upvotes: 32

Views: 25256

Answers (8)

Jacksonkr
Jacksonkr

Reputation: 32247

I might flip keys and values this way:

let arr = "abc".split('');

let flip = []
arr.forEach((n, i) => {
    flip[Object.values(arr)[i]] = Object.keys(arr)[i];
})

console.log(Object.keys(arr), Object.values(arr));
console.log(Object.keys(flip), Object.values(flip));

Depending on how large your initial array is you may want to store the keys/values in their own respective arrays.

Upvotes: 0

XMehdi01
XMehdi01

Reputation: 1

Simple approach

const obj = { a: 'foo', b: 'bar' },
      keys = Object.keys(obj),
      values = Object.values(obj),
      flipped = {};
for(let i=0; i<keys.length; i++){
    flipped[values[i]] = keys[i];
}
console.log(flipped);//{foo: "a", bar: "b"}

Upvotes: 0

Tamlyn
Tamlyn

Reputation: 23592

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'}

Upvotes: 14

redestructa
redestructa

Reputation: 1202

I guess you are talking about Objects not Arrays

function flip(o){
    var newObj = {} 
    Object.keys(o).forEach((el,i)=>{
        newObj[o[el]]=el;
    });
    return newObj;
}

Otherwise it could be

function flip(o){

    var newObj = {} 

    if (Array.isArray(o)){

        o.forEach((el,i)=>{
            newObj[el]=i;
        });

    } else if (typeof o === 'object'){

        Object.keys(o).forEach((el,i)=>{
            newObj[o[el]]=el;
        });

    }

    return newObj;

}

Upvotes: 2

Joseph Avitia
Joseph Avitia

Reputation: 11

The current top answer didn't work as expected for me because key values are offset +1. (and so the returned array tmpArr(0) is also always undefined. So I subtracted 1 from key value and it worked as expected.

function array_flip2 (trans) {
  var key
  var tmpArr = {}

  for (key in trans) {
    if (!trans.hasOwnProperty(key)) {
      continue
    }
    tmpArr[trans[parseInt(key)]-1] = (key)
  }
  return tmpArr
}

Upvotes: 1

Afanasii Kurakin
Afanasii Kurakin

Reputation: 3459

Using underscore _.invert

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

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

Upvotes: 7

ihtus
ihtus

Reputation: 2811

with jQuery:

var array_flipped={};
$.each(array_to_flip, function(i, el) {
  array_flipped[el]=i;
});

Upvotes: 2

Daniel F. Thornton
Daniel F. Thornton

Reputation: 3685

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;
}

Upvotes: 24

Related Questions