Created
December 14, 2010 10:36
-
-
Save fatgy/740249 to your computer and use it in GitHub Desktop.
How to Sort an Associative Array (object) in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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