Last active
November 29, 2021 12:19
-
-
Save btxtiger/d8a5f5ce7726300e7173c203455bc771 to your computer and use it in GitHub Desktop.
TypeScript array natural sort (optional object property)
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
/** | |
* TS array natural sort (optional object property) | |
*/ | |
function naturalObjectSort<T>(arr: T[], objPropertyPath = ''): T[] { | |
return [...arr].sort((a: T, b: T) => { | |
let propPathParts = objPropertyPath.split('.'); | |
const getDeepValue = (obj: T): string => { | |
let value = obj as any; | |
for (let i = 0; i < propPathParts.length; i++) { | |
const propPathPart = propPathParts[i]; | |
value = value[propPathPart]; | |
} | |
return `${value}`; | |
}; | |
return getDeepValue(a).localeCompare(getDeepValue(b), 'en', { numeric: true }); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment