How to Sort an Associative Array (object) in Javascript

I’ve been working on an ajax site that needs to pass parameters elegantly via the hash tag. While working, I realized that there is usability value to a standardized URL (not to mention SEO value, if Google ever indexes such javascript based pages). In any event, I created this function to sort my hash arrays, and figured you might find it useful too:

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;
}

You can construct a demo page with the following HTML:

<html>
<body>
<script type="text/javascript">

// These vars are for demonstration purposes
var alertSort = "";
var blah = {}
blah.test2 = "testb";
blah.test1 = "testa";
blah.test3 = "testc";

// This function sorts objects by key
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]];
		alertSort += "/" + sortedKeys[i] + "=" + arr[sortedKeys[i]];
// This line is for demonstration purposes
	}
    alert(alertSort);   // This line is for demonstration purposes
	return sortedObj;
}

// Call the function
sortObj(blah);

</script>
</body>
</html>
  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Popular Posts

Alternatively, you may want to return to the Home Page to view the most recent blog posts in order. If you have any questions, I make a point of reading and responding to all comments. Thanks for joining!

blog comments powered by Disqus