Skip to content

Instantly share code, notes, and snippets.

@fatgy
Created December 14, 2010 10:36
Show Gist options
  • Save fatgy/740249 to your computer and use it in GitHub Desktop.
Save fatgy/740249 to your computer and use it in GitHub Desktop.
How to Sort an Associative Array (object) in Javascript
// http://www.latentmotion.com/how-to-sort-an-associative-array-object-in-javascript/
function sortObj(arr){
// Setup Arrays
var sortedKeys = new Array();
var sortedObj = {};
// Separate keys and sort them
for (var i in arr){
sortedKeys.push(i);
}
sortedKeys.sort();
// Reconstruct sorted obj based on keys
for (var i in sortedKeys){
sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
}
return sortedObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment