Skip to content

Instantly share code, notes, and snippets.

@halcarleton
Created July 22, 2014 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halcarleton/d0930699bc0e7894b54b to your computer and use it in GitHub Desktop.
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.
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