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.
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.
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;
}
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'}
Using underscore _.invert
_.invert([1, 2])
//{1: '0', 2: '1'}
_.invert({a: 'b', c: 'd'})
//{b: 'a', d: 'c'}
number? Call another method like map?_.mapObject(_.invert([1, 2]), function (d) {return +d}) will doinvert too.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;
}
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
}
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.