Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save JoeChapman/2214358 to your computer and use it in GitHub Desktop.
Sorting an array of objects by more than one key
var arr = [
{first: 'Joseph', last: 'Chapman'},
{first: 'Andrew', last: 'Chapman'},
{first: '234', last: '111'},
{first: 'Joseph', last: 'Hinge'},
{first: 'Simon', last: 'Andrews'},
{first: 'Robert', last: 'Hinge'}
];
var sortBy = function (key, minor) {
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 typeof minor === 'function' ? minor(o, p) : 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}
}
};
arr.sort(sortBy('last', sortBy('first')));
// arr is [{first: '234', last: '111'},
// {first: 'Simon', last: 'Andrews'},
// {first: 'Andrew', last: 'Chapman'},
// {first: 'Joseph', last: 'Chapman'},
// {first: 'Simon', last: 'Andrews'},
// {first: 'Robert', last: 'Hinge'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment