I am writing a function that will sort an array of objects either by property or method value. The following code is working. But how do I improve it? I feel there is a lot of duplicate code in it.
transform(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;
}