Created
July 15, 2015 10:51
-
-
Save thaenor/be12a1c1460c03cc5c69 to your computer and use it in GitHub Desktop.
Awesome reusable JavaScript sorting function FROM: http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects/979325#979325
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
var sort_by = function(field, reverse, primer){ | |
var key = primer ? | |
function(x) {return primer(x[field])} : | |
function(x) {return x[field]}; | |
reverse = !reverse ? 1 : -1; | |
return function (a, b) { | |
return a = key(a), b = key(b), reverse * ((a > b) - (b > a)); | |
} | |
} | |
var homes = [{ | |
"h_id": "3", | |
"city": "Dallas", | |
"state": "TX", | |
"zip": "75201", | |
"price": "162500" | |
}, { | |
"h_id": "4", | |
"city": "Bevery Hills", | |
"state": "CA", | |
"zip": "90210", | |
"price": "319250" | |
}, { | |
"h_id": "5", | |
"city": "New York", | |
"state": "NY", | |
"zip": "00010", | |
"price": "962500" | |
}]; | |
// Sort 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()})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment