Looking for ways to enhance my array sorting function, which currently sorts by property or method value. The existing code is functional, but I believe there's room for improvement due to redundant sections.
optimizeSort(array: any, field: string): any[] {
if (!Array.isArray(array)) {
return;
}
array.sort((a: any, b: any) => {
if (typeof a[field] == 'function' && typeof b[field] == 'function') {
if (a[field]() < b[field]()) {
return -1;
} else if (a[field]() > b[field]()) {
return 1;
} else {
return 0;
}
}
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}