I have an array of objects like so :
[
{key: "key1", label: "1"},
{key: "key2", label: "3"},
{key: "key3", label: "2"},
{key: "key4", label: "Second"},
{key: "key5", label: "First"}
]
I would like to sort this array so the alphabetical values come first like so :
[
{key: "key5", label: "First"},
{key: "key4", label: "Second"},
{key: "key1", label: "1"},
{key: "key3", label: "2"},
{key: "key2", label: "3"}
]
I came up with this solution:
sortArray(list: any[], key: string) {
return list.sort(compare);
function compare(a, b) {
const aIsAlphabetic = isAlphabetical(a[key]);
const bIsAlphabetic = isAlphabetical(b[key]);
if (aIsAlphabetic && !bIsAlphabetic) {
return -1;
} else if (bIsAlphabetic && !aIsAlphabetic) {
return 1;
}
if (a[key] < b[key]) {
return -1;
}
if (a[key] > b[key]) {
return 1;
}
return 0;
}
function isAlphabetical(value: string) {
return value.match(/[a-zA-Z]/i);
}
}
The solution works, but I don't like the idea of declaring several functions inside of sortArray, am I doing it right? Or are there any other tips to make properly?