Skip to content

Instantly share code, notes, and snippets.

@bsitruk
Created June 14, 2022 05:48
Show Gist options
  • Save bsitruk/942331a882fc81922c59111cb9531bb0 to your computer and use it in GitHub Desktop.
Save bsitruk/942331a882fc81922c59111cb9531bb0 to your computer and use it in GitHub Desktop.
// 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