32

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.

0

8 Answers 8

24

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

@pianoman - I added the hasOwnProperty check. Hope you don't mind =)
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!
also keep in mind that this only works reliably if the property values have a unique string representation
@Christoph - See your point, but if the properties aren't unique, one really shouldn't be flipping the array to begin with ಠ_ಠ
14

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

Comments

7

Using underscore _.invert

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

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

3 Comments

Good solution, but how would you cast the string value, which are the array indices, to type number? Call another method like map?
@ConAntonakos yes, I guess _.mapObject(_.invert([1, 2]), function (d) {return +d}) will do
For those using lodash, it has invert too.
2

with jQuery:

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

Comments

2

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;

}

1 Comment

The .map function doesn't work at all, it only creates an array of ascending numbers from 0 to length-1 regardless of array content.
1

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
}

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.