Skip to content

Instantly share code, notes, and snippets.

@JoeChapman
Created March 27, 2012 08:27
Show Gist options
  • Select an option

  • Save JoeChapman/2213994 to your computer and use it in GitHub Desktop.

Select an option

Save JoeChapman/2213994 to your computer and use it in GitHub Desktop.
Sorting an array of objects by key
var arr = [
{first: 'Joseph', last: 'Smith'},
{first: 'Joseph', last: 'Chapman'},
{first: 'Joseph', last: 'Hinge'}
];
var sortBy = function (key) {
return function (o, p) {
var a, b;
if (o && p && typeof o === 'object' && typeof p === 'object') {
a = o[key];
b = p[key];
if (a === b) {
return 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}
}
};
arr.sort(sortBy('last'));
// arr is [{first: 'Joseph', last: 'Chapman'}, {first: 'Joseph', last: 'Hinge'}, {first: 'Joseph', last: 'Smith'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment