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.
/**
* 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) );
});
}
}
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.




Subchild is a blog about web development. It's author is Aleksandar Kolundzija, himself a web developer
for 10++ years, presently a Hacker-in-Residence at betaworks. Prior to betaworks, Alex worked at Google, Meebo,
MLB Advanced Media (MLB.com), Razorfish, and elsewhere.
SJ says:
September 29th, 2012 at 9:50 am
If the array size exceeded 10 then sorting will not work. any help?