Created
April 20, 2023 21:10
-
-
Save AleksejDix/43c40c9bcab6dffd7ce6849e3dc97f44 to your computer and use it in GitHub Desktop.
Compare
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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