Skip to content

Instantly share code, notes, and snippets.

@anabarasan
Last active August 29, 2015 14:19
Show Gist options
  • Save anabarasan/3371ecd8a688083071b8 to your computer and use it in GitHub Desktop.
Save anabarasan/3371ecd8a688083071b8 to your computer and use it in GitHub Desktop.
compare function for use in Array.sort()
function compare(property, reverse) {
return function cmp(obj1, obj2) {
if (property) {
obj1 = obj1[property];
obj2 = obj2[property];
}
if (typeof obj1 === 'string' || obj1 instanceof String) {
var result = obj1.localeCompare(obj2);
return reverse ? 0 - result : result;
}
if (reverse)
return (obj1 < obj2) ? 1 : (obj1 > obj2) ? -1 : 0;
else
return (obj1 < obj2) ? -1 : (obj1 > obj2) ? 1 : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment