Skip to content

Instantly share code, notes, and snippets.

@AleksejDix
Created April 20, 2023 21:10
Show Gist options
  • Save AleksejDix/43c40c9bcab6dffd7ce6849e3dc97f44 to your computer and use it in GitHub Desktop.
Save AleksejDix/43c40c9bcab6dffd7ce6849e3dc97f44 to your computer and use it in GitHub Desktop.
Compare
function compare(a, b, key, order) {
if (a[key] === b[key]) {
return 0;
}
if (a[key] === null || a[key] === undefined) {
return order === 'asc' ? -1 : 1;
}
if (b[key] === null || b[key] === undefined) {
return order === 'asc' ? 1 : -1;
}
if (typeof a[key] === 'number' && typeof b[key] === 'number') {
return order === 'asc' ? a[key] - b[key] : b[key] - a[key];
}
if (a[key] instanceof Date && b[key] instanceof Date) {
return order === 'asc' ? a[key] - b[key] : b[key] - a[key];
}
// For other types, like string, use localeCompare
return order === 'asc' ? a[key].localeCompare(b[key]) : b[key].localeCompare(a[key]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment