Created
October 4, 2021 21:21
-
-
Save juliandavidmr/0675ebd8e85d2b7815db729635672777 to your computer and use it in GitHub Desktop.
Order any array by number attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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