Created
April 11, 2013 22:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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