Last active
July 6, 2018 12:14
-
-
Save danutzcodrescu/ef8f19d94c78cf36facbb7bc6fe8f32e to your computer and use it in GitHub Desktop.
sorting methods for a javascript objects array
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
import { isString } from "util"; | |
export function sort(data, order, column) { | |
return data.sort((a, b) => { | |
const first = isString(a[column]) ? a[column].toLowerCase() : a[column]; | |
const second = isString(b[column]) ? b[column].toLowerCase() : b[column]; | |
if (order === "asc") { | |
if (first < second) { | |
return -1; | |
} else if (first > second) { | |
return 1; | |
} else { | |
return 0; | |
} | |
} else { | |
if (first > second) { | |
return -1; | |
} else if (first < second) { | |
return 1; | |
} else { | |
return 0; | |
} | |
} | |
}); | |
} | |
const collator = new Intl.Collator(undefined, { | |
numeric: true, | |
sensitivity: "variant" | |
}); | |
export function sortWithCollator(data, order, column) { | |
const sorted = data.sort((a, b) => { | |
return collator.compare(a[column], b[column]); | |
}); | |
if (order === "desc") sorted.reverse(); | |
return sorted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment