Skip to content

Instantly share code, notes, and snippets.

@btxtiger
Last active November 29, 2021 12:19
Show Gist options
  • Save btxtiger/d8a5f5ce7726300e7173c203455bc771 to your computer and use it in GitHub Desktop.
Save btxtiger/d8a5f5ce7726300e7173c203455bc771 to your computer and use it in GitHub Desktop.
TypeScript array natural sort (optional object property)
/**
* 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