Skip to content

Instantly share code, notes, and snippets.

@watagashi
Created July 14, 2011 14:55
Show Gist options
  • Save watagashi/1082610 to your computer and use it in GitHub Desktop.
Save watagashi/1082610 to your computer and use it in GitHub Desktop.
var n = [4, 8, 15, 23, 42];
n.sort();
n.sort(function(a, b) {
return a-b;
});
var m = ['aa', 'bb', 'a', 4, 8, 15, 16, 23, 42];
m.sort(function(a, b) {
if (a === b) {
return 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
});
var by = function (name) {
return function (o, p) {
var a, b;
if (typeof o === 'object' && typeof p === 'object' && o &&p) {
a = o[name];
b = p[name];
if (a === b) {
return 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
} else {
throw {
name: 'Error',
message: name + ' を含むオブジェクトが必要です。'
};
}
};
};
var s = [
{first: 'Joe', last: 'Besser'},
{first: 'Moe', last: 'Howard'},
{first: 'Joe', last: 'DeRita'},
{first: 'Shemp', last: 'Howard'},
{first: 'Larry', last: 'Fine'},
{first: 'Curly', last: 'Howard'}
];
s.sort(by('first'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment