Sort an Array of Objects by Key

Sorts an array of objects by a specified key in ascending or descending order.

TypeScript
david

13 weeks ago

function sortByKey<T extends Record<string, any>, K extends keyof T>(
  array: T[],
  key: K,
  ascending: boolean = true
): T[] {
  return array.sort((a, b) =>
    ascending ? (a[key] > b[key] ? 1 : -1) : (a[key] < b[key] ? 1 : -1)
  );
}
0