• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Sorting By Vote Count & Recently Added Date In Javascript

Javascript · August 15, 2016

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).

Dwayne

Leave a Reply Cancel reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
David Millican
David Millican
5 years ago

Anyone know of a clean way to do this for string values other than using the conditional pattern of returning 1 if a > b otherwise returning -1?

0

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Which Neural DSP Archetype Plugins Should You Buy?
  • Smoke Detector Randomly Goes Off Early Hours of The Morning
  • How To Mock uuid In Jest
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • Web 3.0 may have died before it even started
  • Deno Raises $21M - but is anyone using it yet?
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • How To Install Eufy Security Cameras Without Drilling or Using Screws

Recent Comments

  • Jay on Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • john on Deno Raises $21M – but is anyone using it yet?
  • Oranges on How To Store Users In Firestore Using Firebase Authentication
  • Precious on Fixing Sequel Pro SQL Encoding Error For Imported SQL Files
  • James on A List of WordPress Gutenberg Core Blocks

Copyright © 2022 · Dwayne Charrington · Log in

wpDiscuz