I wrote this one today while trying to recreate _.sortBy
in TypeScript, and thought I would leave it for anyone in need.
// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key]
export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
return list.sort((a, b): number => {
const _a = getKeyValue<keyof T, T>(index)(a)
const _b = getKeyValue<keyof T, T>(index)(b)
if (_a < _b) return -1
if (_a > _b) return 1
return 0
})
}
It expects an array of generic type T, hence the cast for <T extends {}>
, as well as typing the parameter and function return type with T[]
const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)
** getByKey
fn found here