I have an object TaskItemVO
with field dueDate
which has the type Date
:
export class TaskItemVO { public dueDate: Date; }
I have this method which I call when I try to sort by date but it is not working:
public sortByDueDate(): void { this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => { return a.dueDate - b.dueDate; }); }
I get this error in the return line of method:
The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
So what is the correct way of sorting array by date fields in TypeScript?
To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.
Array. sort() function sorts an Array. The Sort() function will sort array using the optional compareFunction provided, if it is not provided Javascript will sort the array object by converting values to strings and comparing strings in UTF-16 code units order.
Just sort lessons using Array. prototype. sort() in your component class before you bind it. You need to show how your lessons property is populated and what format the date property is in as well as if you mean descending or ascending order.
Try using the Date.getTime() method:
public sortByDueDate(): void { this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => { return a.dueDate.getTime() - b.dueDate.getTime(); }); }
^ Above throws error with undefined date so try below:
If you want to handle undefined:
private getTime(date?: Date) { return date != null ? date.getTime() : 0; } public sortByDueDate(): void { this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => { return this.getTime(a.dueDate) - this.getTime(b.dueDate); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With