Sorting By Vote Count & Recently Added Date In Javascript

Recently whilst working on my web app Built With Aurelia I encountered a situation where I needed to sort by the highest upvoted items, but also sort secondly by the recently added items.

The collection of items would look like this:

  • Item 1 (5 votes)
  • Item 2 (3 votes)
  • Item 3 (2 votes)
  • Item 4 (2 votes)
  • Item 5 (1 vote)
  • Item 6 (1 vote)
  • Item 7 (0 votes)
  • Item 8 (0 votes)
  • Item 9 (0 votes)
  • Item 10 (0 votes)

The code that I wrote to achieve this was the following using the sort method in Javscript:

this.projects.sort((a, b) => {
    return parseInt(b.votes, 10) - parseInt(a.votes, 10) || a.added - b.added;
});

Essentially the way this works is if the votes for items a and b are different, then the sort is based on the vote count. If the vote values are the same, then the first expression returns 0 (falsey) and the second expression is used.

Technically you could have multiple variables for sorting, but in my case I just needed to sort by vote count and then sort by recently added date (Unix timestamp).