Created
August 22, 2012 08:16
-
-
Save theskumar/3423710 to your computer and use it in GitHub Desktop.
js: sort_by function
This file contains hidden or 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
// reusable sort functions, and sort by any field | |
// UsagesSort by price high to low | |
// homes.sort(sort_by('price', true, parseInt)); | |
// Sort by city, case-insensitive, A-Z | |
// homes.sort(sort_by('city', false, function(a){return a.toUpperCase()})); | |
var sort_by = function(field, reverse, primer){ | |
var key = function (x) {return primer ? primer(x[field]) : x[field];}; | |
return function (a,b) { | |
var A = key(a), B = key(b); | |
return (((A < B) ? -1 : | |
(A > B) ? +1 : 0)) * [-1,1][+!!reverse]; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment