Created
June 14, 2022 05:48
-
-
Save bsitruk/942331a882fc81922c59111cb9531bb0 to your computer and use it in GitHub Desktop.
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
// Sort List of Objects By Two Keys | |
type SortKey<T> = { | |
key: keyof T; | |
order: 1 | -1; | |
}; | |
export function sortByKeys<T>(list: T[], keys: SortKey<T> | [SortKey<T>, SortKey<T>]) { | |
if (!Array.isArray(keys)) { | |
const { key: sortKey, order } = keys; | |
return list.sort((v1, v2) => (v1[sortKey] < v2[sortKey] ? order * 1 : -1 * order)); | |
} | |
const [{ key: firstSortKey, order: firstOrder }, { key: secondSortKey, order: secondOrder }] = keys; | |
return list.sort((v1, v2) => { | |
if (v1[firstSortKey] === v2[firstSortKey]) { | |
return v1[secondSortKey] < v2[secondSortKey] ? secondOrder * 1 : -1 * secondOrder; | |
} | |
return v1[firstSortKey] < v2[firstSortKey] ? firstOrder * 1 : -1 * firstOrder; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment