Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save JoeChapman/2215779 to your computer and use it in GitHub Desktop.
Sorting an array of nested objects
var arr = [
{details: {name: {first: 'Joseph', last: 'Chapman'}}},
{details: {name: {first: 'Andrew', last: 'Chapman'}}},
{details: {name: {first: '234', last: '111'}}},
{details: {name: {first: 'Joseph', last: 'Hinge'}}},
{details: {name: {first: 'Simon', last: 'Andrews'}}},
{details: {name: {first: 'Robert', last: 'Hinge'}}}
];
var sortBy = function (key, minor) {
var compare = function (a, b, o, p) {
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;
}
return function (o, p) {
var a, b, keys, tmp, i, l, n = 0;
if (o && p && typeof o === 'object' && typeof p === 'object') {
keys = key.split(' ');
if (keys.length > 1) {
i = keys.length-1;
while (n++ < i) {
tmp = keys[n];
for (l in o) {
if (o.hasOwnProperty(l) && typeof o[l][tmp] !== 'undefined') {
if (typeof o[l][tmp][keys[i]] !== 'object') {
a = o[l][tmp][keys[i]];
b = p[l][tmp][keys[i]];
break;
} else {
continue;
}
}
}
}
} else {
a = o[key];
b = p[key];
}
return compare(a, b, o, p);
}
}
};
arr.sort(sortBy('details name last', sortBy('details name first')));
// arr is [
// {first: '234', last: '111'},
// {first: 'Simon', last: 'Andrews'},
// {first: 'Andrew', last: 'Chapman'},
// {first: 'Joseph', last: 'Chapman'},
// {first: 'Joseph', last: 'Hinge'},
// {first: 'Robert', last: 'Hinge'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment