Created
January 8, 2016 12:04
-
-
Save ukcoderj/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 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
// 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