In my TypeScript code, I am faced with the challenge of sorting an array of Objects based on the actual object name rather than a key within the object. Each object in the array contains a "name" key that corresponds to the name of the object itself. Despite my efforts to sort by the name key using the .sort() function, I have not been successful.
Here is a sample array:
templateReports = [
{"Project Report": {name: "Project Report", docType: "Project"}},
{"Department Report": {name: "Department Report", docType: "Department"}},
{"Room Report": {name: "Room Report", docType: "Room"}}
]
I attempted to use the .sort() function as follows:
templateReports.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
However, this method did not work because accessing the name key requires syntax like
templateReports[0]["Project Report"].name
. Therefore, I need to adjust my logic to something like:
templateReports.sort((a,b) => (a[nameOfObject].name > b[nameOfNextObject].name) ? 1 : ((b[nameOfNextObject].name > a[nameOfObject].name) ? -1 : 0));
My goal is to sort the objects alphabetically as shown below:
templateReports = [
{"Department Report": {name: "Department Report", docType: "Department"}},
{"Project Report": {name: "Project Report", docType: "Project"}},
{"Room Report": {name: "Room Report", docType: "Room"}}
]
If anyone can offer guidance on how to achieve this through the sort method or any alternative approach, I would greatly appreciate it. Thank you.