Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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