Skip to content

Commit 0979981

Browse files
committed
Add util
1 parent f99751a commit 0979981

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/utils/index.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,3 +150,17 @@ export function elapsedBefore(
150150
throw new Error(type);
151151
}
152152
}
153+
154+
export function sortByKey<T extends Record<string, any>>(array: T[], key: keyof T): T[] {
155+
return array.sort((a, b) => {
156+
const av = a[key] as any;
157+
const bv = b[key] as any;
158+
159+
if (av == null) return -1;
160+
if (bv == null) return 1;
161+
if (typeof av === "number" && typeof bv === "number") return av - bv;
162+
if (av instanceof Date && bv instanceof Date) return av.getTime() - bv.getTime();
163+
164+
return av === bv ? 0 : av > bv ? 1 : -1;
165+
});
166+
}

0 commit comments

Comments
 (0)