Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juliandavidmr/0675ebd8e85d2b7815db729635672777 to your computer and use it in GitHub Desktop.
Save juliandavidmr/0675ebd8e85d2b7815db729635672777 to your computer and use it in GitHub Desktop.
Order any array by number attribute
export function orderArrayByNumberAttribute<T>(
array: T[],
attribute: keyof T,
order: 'asc' | 'desc',
): T[] {
return array.sort((a, b) => {
const aValue = a[attribute];
const bValue = b[attribute];
if (order === 'asc') {
// @ts-expect-error
return aValue - bValue;
}
// @ts-expect-error
return bValue - aValue;
});
}
console.log(
'Ordered',
orderArrayByNumberAttribute(
myArray,
'countNumberAttr',
'desc',
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment