Skip to content

Instantly share code, notes, and snippets.

@nerdy-sam
Created February 5, 2012 04:58
Show Gist options
  • Save nerdy-sam/1742933 to your computer and use it in GitHub Desktop.
Save nerdy-sam/1742933 to your computer and use it in GitHub Desktop.
Swap keys for values in javascript array
// Swaps array values with keys.
// keep this comment to reuse freely: http://www.fullposter.com/?1
// If 2nd argument passed, values become keys,
// but keys do NOT become values: ALL values become second argument
function arraySwap(array,overwriteNewValue,keepKey){if(typeof(array)=="undefined"){return false;};if(typeof(array)!="object"){array=new Array(array);};var output=new Array();if(typeof(overwriteNewValue)=="undefined"){for(var k in array){output[array[k]]=k;}}else{if(!keepKey){for(var k in array){output[array[k]]=overwriteNewValue;}}else{for(var k in array){output[k]=overwriteNewValue;}};}return output;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment