Skip to content

Instantly share code, notes, and snippets.

@codenamejason
Created December 12, 2017 14:33
Show Gist options
  • Save codenamejason/d0e9222c197ecc33de863208590ca87b to your computer and use it in GitHub Desktop.
Save codenamejason/d0e9222c197ecc33de863208590ca87b to your computer and use it in GitHub Desktop.
Sort an object
var sort_by = function() {
var fields = [].slice.call(arguments),
n_fields = fields.length;
return function(A, B) {
var a, b, field, key, primer, reverse, result;
for (var i = 0, l = n_fields; i < l; i++) {
result = 0;
field = fields[i];
key = typeof field === 'string' ? field : field.name;
a = A[key];
b = B[key];
if (typeof field.primer !== 'undefined') {
a = field.primer(a);
b = field.primer(b);
}
reverse = (field.reverse) ? -1 : 1;
if (a < b) result = reverse * -1;
if (a > b) result = reverse * 1;
if (result !== 0) break;
}
return result;
}
}
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": "6",
"city": "Dallas",
"state": "TX",
"zip": "75000",
"price": "556699"},
{
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"}
];
homes.sort(sort_by('city', {
name: 'price',
primer: parseInt,
reverse: true
}));
console.log(homes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment