Reputation: 3403
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
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
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
Reputation: 23592
const example = { a: 'foo', b: 'bar' };
const flipped = Object.entries(example)
.reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {});
// flipped is {foo: 'a', bar: 'b'}
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
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
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
Reputation: 3459
Using underscore _.invert
_.invert([1, 2])
//{1: '0', 2: '1'}
_.invert({a: 'b', c: 'd'})
//{b: 'a', d: 'c'}
Upvotes: 7
Reputation: 2811
with jQuery:
var array_flipped={};
$.each(array_to_flip, function(i, el) {
array_flipped[el]=i;
});
Upvotes: 2
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