Skip to content

Instantly share code, notes, and snippets.

@subchild
Created April 13, 2010 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subchild/364254 to your computer and use it in GitHub Desktop.
Save subchild/364254 to your computer and use it in GitHub Desktop.
sortJsonArrayByProp()
/**
* 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]];
}
}
return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment