sortBy()
asc
code:ts
export const sortBy = <T>(predicate: (a: T) => any) => (a: T, b: T) =>
predicate(a) > predicate(b) ? 1 : predicate(b) > predicate(a) ? -1 : 0;
desc版
code:ts
export const sortDescBy = <T>(predicate: (a: T) => any) => (a: T, b: T) =>
predicate(a) > predicate(b) ? -1 : predicate(b) > predicate(a) ? 1 : 0;
使用例
code:ts
arr.sort(sortBy(a=>a.userId))
JSの.sort()って「破壊的変更かつ新しい値を返す」んだね