Created
January 24, 2012 15:39
-
-
Save orip/1670739 to your computer and use it in GitHub Desktop.
Javascript advanced sorter
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
/** | |
* Create a compare function for Javascript's Array.sort() | |
* Inspired by Triptych's http://stackoverflow.com/a/979325/37020 | |
* | |
* my_array.sort( sorter({key: 'size', reverse: true}) ); | |
* my_array.sort( sorter({key: function(x) { return parseInt(x.tag); }) ); | |
*/ | |
var sorter = function(spec) { | |
if (spec.key === undefined) | |
spec.key = function(x) { return x; }; // identity | |
if (spec.reverse === undefined) | |
spec.reverse = false; | |
// either a field name, or a key function | |
var key = typeof spec.key === "string" ? function(x) { return x[spec.key]; } : spec.key; | |
return function (a,b) { | |
var A = key(a), B = key(b); | |
var cmp = A < B ? -1 : A > B ? 1 : 0; | |
return spec.reverse ? -1 * cmp : cmp; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment