Created
April 13, 2010 02:30
-
-
Save subchild/364254 to your computer and use it in GitHub Desktop.
sortJsonArrayByProp()
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
/** | |
* 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