Skip to content

Instantly share code, notes, and snippets.

@employee451
Created May 30, 2022 11:59
Show Gist options
  • Save employee451/d648f45e0e4879f75a6f18552ccc9337 to your computer and use it in GitHub Desktop.
Save employee451/d648f45e0e4879f75a6f18552ccc9337 to your computer and use it in GitHub Desktop.
type AcceptedArrayContents = string | { [key: string]: any }
/**
* Sorts an array alphabetically. If an object is provided, it sorts by the provided sortProperty.
* @param array
* @param sortProperty
*/
const sortArrayAlphabetically = (
array: AcceptedArrayContents[] = [],
sortProperty = ''
): any[] => {
return array.sort((a: AcceptedArrayContents, b: AcceptedArrayContents) => {
const textA = (typeof a === 'string' ? a : a[sortProperty]).toUpperCase()
const textB = (typeof b === 'string' ? b : b[sortProperty]).toUpperCase()
return textA.localeCompare(textB)
})
}
export default sortArrayAlphabetically
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment