Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript sort by date not working

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?

like image 808
CommonSenseCode Avatar asked Oct 25 '16 19:10

CommonSenseCode


People also ask

How do I sort dates 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.

How do I sort objects in TypeScript?

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.

How does angular sort dates?

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.


1 Answers

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:


Edit

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);     }); } 
like image 109
Nitzan Tomer Avatar answered Oct 07 '22 16:10

Nitzan Tomer