szarancza ze spizu
szarancza ze spizu

Reputation: 87

Sort Objects in angular 2+

I have weird problem. I have simple Comment Interface:

export interface Comment {
  time: number;
  text: string;
}

Time shows how much days passed since adding. I want to sort an array of Comment with my sort function:

comments.sort((a, b) => {
  if (a.time < b.time) return -1;
  if (a.time > b.time) return 1;
  return 0;
})

The problem is, when the comments are having the same days value. They seems unsorted. When I adding new comment I want that comment to be on top. How To fix it?

Link to problem: stackblitz

Upvotes: 0

Views: 476

Answers (2)

Nevliin
Nevliin

Reputation: 11

If your only parameter for sorting is the day the comment was created on, you can't really have a more specific order than you already do as there is no way to figure out which comments were added earlier and later on that day. To have a chronological order, you can replace 'time: number' with 'time: Date', giving you millisecond precision in sorting the Comments.

Interface:

export interface Comment {
    time: Date;
    text: string;
}

Adding new comment:

this.comments.push(
  {text: commentText, date: new Date()}
)

this.comments = comments.sort((a: Comment, b: Comment) => {
    return b.date.getTime() - a.date.getTime();
})

This will display the comments in chronological order; the newest comments are at the top, oldest at the bottom. To reverse this order, just switch 'a' and 'b' in the short function.

When adding a new comment, just call the Date()-constructor to get the current time. If you only want to display the day the comment was created on, you can do so with the getDate() method of Date (All methods are documented here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date)

OR

If you have no interest in a persistent order, you could simply add new entries a the start of the array:

this.comments.unshift(
   {text: commentText, date: new Date()}
);

Also, some best practices:

  • Actually implement the interface you pasted above and use it for typing your variables.
  • Avoid 'any' wherever you can, as it will void the advantages TypeScript provides to you.

Hope I could help.

Upvotes: 1

Ringo
Ringo

Reputation: 621

Quick fix

just put latest on top before you sort.

 onAddCommentEnter(commentText) {
   this.comments = [{text: commentText, date: 0}, ...this.comments].sort((a, b) => {
     if (a.date < b.date) return -1;
     if (a.date > b.date) return 1;
    return 0;
  })
}

https://stackblitz.com/edit/angular-2ggm4v

Upvotes: 2

Related Questions