You can define a function like
function sortBy<T, V>(
array: T[],
valueExtractor: (t: T) => V,
comparator?: (a: V, b: V) => number) {
// note: this is a flawed default, there should be a case for equality
// which should result in 0 for example
const c = comparator ?? ((a, b) => a > b ? 1 : -1)
return array.sort((a, b) => c(valueExtractor(a), valueExtractor(b)))
}
which then could be used like
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[] = sortBy(arr, t => t.a)
const sortedC: Type[] = sortBy(arr, t => t.c)
// or if you need a different comparison
const sortedX = sortBy(arr, t => t.c, (a, b) => a.getDay() - b.getDay())
This also works with nested properties within objects t => t.a.b.c or for cases where you need to derive the sort key further e.g. t => t.a.toLowerCase()
sort((a,b) => a[property] > b[property] ? 1 : -1). IMO, this is verbose, so I was hoping from something a little slicker.