Looking for a solution to sort a table in an Angular project? The challenge is sorting by either a direct property of objects in the array or a child of that property. Take, for instance, sorting by associate.lastname
versus associate.client.name
. I've managed to accomplish this within a single TypeScript method.
Here's the code snippet for the sortBy
method within my component's class:
sortBy(option: SortOption, sortedBy: string) {
const props = option.split('.');
const parent = props[0];
const child = props[1];
const asc = this[sortedBy];
if (!child) {
// Sorting logic for when only parent property is involved
} else {
// Sorting logic for when both parent and child properties are involved
}
this[sortedBy] = !this[sortedBy]
}
This method effectively handles different scenarios depending on whether there is a child property to be considered. However, I'm curious to know if there's a more concise way to achieve the same results. Despite the similarity between the if and else statements, I can't seem to find a cleaner approach.
Do you have any suggestions for improving this method?