Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active March 29, 2024 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/fdab16fce317caa9a0919ae5e0e1b9dc to your computer and use it in GitHub Desktop.
Save ryanmorr/fdab16fce317caa9a0919ae5e0e1b9dc to your computer and use it in GitHub Desktop.
Sort an array by string, number, or date with support for ascending and descending order
function compareDefault(a, b) {
return a - b;
}
function compareStrings(a, b) {
a = String(a).toUpperCase();
b = String(b).toUpperCase();
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
}
function compareNumbers(a, b) {
a = typeof a === 'number' ? a : parseFloat(a, 10);
b = typeof b === 'number' ? b : parseFloat(b, 10);
return (Number.isNaN(a) ? 0 : a) - (Number.isNaN(b) ? 0 : b);
}
function compareDates(a, b) {
a = typeof a === 'string' ? Date.parse(a) : a.getTime();
b = typeof b === 'string' ? Date.parse(b) : b.getTime();
return (Number.isNaN(a) ? 0 : a) - (Number.isNaN(b) ? 0 : b);
}
function getComparator(type) {
if (typeof type === 'function') {
return type;
}
if (type === 'string') {
return compareStrings;
}
if (type === 'number') {
return compareNumbers;
}
if (type === 'date') {
return compareDates;
}
}
function sort(array, type = compareDefault, dir = 'ASC') {
const compare = getComparator(type);
array.sort(dir === 'ASC' ? compare : (a, b) => ~compare(a, b) + 1);
}
// Usage:
const items = [
10.5,
10.2,
20,
5.5,
2,
50,
5
];
sort(items, 'number', 'DESC');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment