Created
July 22, 2014 13:47
-
-
Save halcarleton/d0930699bc0e7894b54b to your computer and use it in GitHub Desktop.
A function which allows you to sort an array of objects by properties of the objects.
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
function byProperty (prop, reverse, primer) { | |
if (typeof reverse === 'undefined') { reverse = false; } | |
if (typeof primer !== 'function') { primer = false; } | |
var key = primer | |
? function(x) {return primer(x[prop]);} | |
: function(x) {return x[prop];}; | |
reverse = [1, -1][+!!reverse]; | |
return function (a, b) { | |
a = key(a), | |
b = key(b); | |
return reverse * ((a > b) - (b > a)); | |
}; | |
} | |
/* Example usage */ | |
var arr = [ | |
{ a: "5", b: "e"}, | |
{ a: "10", b: "j"}, | |
{ a: "2", b: "b"}, | |
{ a: "6", b: "f"} | |
]; | |
arr.sort(byProperty(a, true, funtion(x){return parseInt(x,10);})); | |
console.log(arr); | |
/* | |
Result: | |
[ | |
{ a: "2", b: "b" }, | |
{ a: "5", b: "e" }, | |
{ a: "6", b: "f" }, | |
{ a: "10", b: "j" } | |
] | |
*/ | |
/* Note: This snippet was originally taken from a stackoverflow answer. I have published it here for my own reference. */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment