To create a custom sorting function, you can use the following structure:
function sortByCustom<T, V>(
array: T[],
valueExtractor: (t: T) => V,
comparator?: (a: V, b: V) => number) {
// Note that this default comparison logic is basic and may need adjustment
const c = comparator ?? ((a, b) => a > b ? 1 : -1)
return array.sort((a, b) => c(valueExtractor(a), valueExtractor(b)))
}
You can then utilize it like this:
interface Type { a: string, b: number, c: Date }
const arr: Type[] = [
{ a: '1', b: 1, c: new Date(3) },
{ a: '3', b: 2, c: new Date(2) },
{ a: '2', b: 3, c: new Date(1) },
]
const sortedA: Type[] = sortByCustom(arr, t => t.a)
const sortedC: Type[] = sortByCustom(arr, t => t.c)
// If you require a different comparison method
const sortedX = sortByCustom(arr, t => t.c, (a, b) => a.getDay() - b.getDay())
This function also supports nested properties within objects like t => t.a.b.c
or other scenarios where additional transformation of sort keys is needed, such as t => t.a.toLowerCase()