Skip to content

Instantly share code, notes, and snippets.

@skipjac
Created April 11, 2013 22:49
Show Gist options
  • Save skipjac/5367832 to your computer and use it in GitHub Desktop.
Save skipjac/5367832 to your computer and use it in GitHub Desktop.
This will sort a bunch of objects in a array by a object property
sortJsonArrayByProperty: function(objArray, prop, direction){
if (arguments.length<2) throw new Error("sortJsonArrayByProp requires 2 arguments");
var direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending
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*direct : ((a > b) ? 1*direct : 0) );
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment