Skip to content

Instantly share code, notes, and snippets.

@JsAndDotNet
Created January 8, 2016 12:04
Show Gist options
  • Save JsAndDotNet/033b07593f5a598a07e3 to your computer and use it in GitHub Desktop.
Save JsAndDotNet/033b07593f5a598a07e3 to your computer and use it in GitHub Desktop.
OrderBy on Array based on Properties, taken from Javscript: The Good Parts, by Douglas Crockford
// This might need tweaking for uppercase/lowercase comparisons
// Source - Javscript: The Good Parts, by Douglas Crockford
var by = function (name, minor) {
// Array sorting
// myArray.sort(by('FirstName', by('LastName')));
return function (o, p) {
var a, b;
if (typeof o === 'object' && typeof p === 'object' && o && p) {
a = o[name];
b = p[name];
if (a === b) {
return typeof minor === 'function' ? minor(o, p) : 0;
}
else if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
} else {
throw {
name: 'Error',
message: 'Expected an object when sorting by ' + name
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment