0

I'm having trouble understanding the usage of the Array.sort function. I have an array that looks like this:

[
  {
    "votes": 3,
    "suggestedDate": "2019-12-01T01:13:00.978Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2020-05-14T21:55:05.879Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2019-12-01T03:22:40.848Z"
  }
]

I'm currently using things.sort((a, b) => b.votes - a.votes) but this results in a random order when the votes are equal. What sort function should I use to get a stable, date based order when votes are equal?

Hum4n01d
  • 1,312
  • 3
  • 15
  • 30

1 Answers1

1

What sort function should I use to get a stable, date based order when votes are equal?

Well, you can extend existing array.sort callback and check if votes are equal. If so, I think suggestedDate would be another parameter to overall rank

const things = [{
    "votes": 3,
    "suggestedDate": "2019-12-01T01:13:00.978Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2020-05-14T21:55:05.879Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2019-12-01T03:22:40.848Z"
  }
]

things.sort((a, b) => {

  if (b.votes === a.votes) {
    return new Date(b.suggestedDate) - new Date(a.suggestedDate)
  }

  return b.votes - a.votes

})

console.log(things);

Also consider checking this question as @John mentioned

Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50