Sortable object

To follow up of Wolfram's blog about sorting an object hash by values, I thought i'd make a simple function to work on most single key-pair objects, the JavaScript version of an associative array:

 
var obj = {
	car: 300, bike:60, motorbike:200, airplane:1000,
	helicopter: 500, rocket: 8*60*60
};
 
function sortObj(theObj, idx){
	// summary: sort an object hash by a numerical value
	var sortable = [];
	for(var i in theObj){
		sortable.push([i, theObj[i]]);
	}
 
	sortable.sort(function(a,b){
		return a[idx] - b[idx];
	});
 
	var newObj = {};
	dojo.forEach(dojo.map(sortable,function(elm){
		return elm[0];
	}), function(elm){
		newObj[elm] = theObj[elm];
	});
	return newObj;
}
 
console.log(sortObj(obj,1));
 

Leave a comment

You must be logged in to post a comment.