Sorting a JSON Array by Property

Sorting arrays of JSON objects is a task that I occasionally come across. Here’s a little utility I’ve been using for a while that does the trick.

[code='js']
/**
 * Sorts an array of json objects by some common property, or sub-property.
 * @param {array} objArray
 * @param {array|string} prop Dot-delimited string or array of (sub)properties
 */
function sortJsonArrayByProp(objArray, prop){
	if (arguments.length<2){
		throw new Error("sortJsonArrayByProp requires 2 arguments");
	}
	if (objArray && objArray.constructor===Array){
		var propPath = (prop.constructor===Array) ? prop : prop.split(".");
		objArray.sort(function(a,b){
			for (var p in propPath){
				if (a[propPath[p]] && b[propPath[p]]){
					a = a[propPath[p]];
					b = b[propPath[p]];
				}
			}
			// convert numeric strings to integers
			a = a.match(/^\d+$/) ? +a : a;
			b = b.match(/^\d+$/) ? +b : b;
			return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
		});
	}
}
[/code]

Here’s a simple example:

var arr = [
	{name:"Zack", friends:{count:50}},
	{name:"Alex", friends:{count:80}},
	{name:"Mike", friends:{count:30}}
];
sortJsonArrayByProp(arr, "name");
sortJsonArrayByProp(arr, "friends.count");
sortJsonArrayByProp(arr, ["friends","count"]);

[Update] This function now converts strings made up entirely of digits into integers for (presumably) more accurate comparisons, and therefore, sorting.