lbpeppers lbpeppers - 17 days ago 5
Javascript Question

Sorting arrays with multiple keys and with Date easy method JavaScript

I have an array of objects with two keys:


  1. Score

  2. Date



I need to sort the array in reverse order, from highest to lowest. I have this code to sort the array by score:

highscores.sort(function(a, b) {
return b.score - a.score;
});


I'd like to sort it by date also if the score values are equals, i.e.

Array = [
{score: 200, date: 11/11/2016},
{score: 300, date: 11/11/2016},
{score: 200, date: 12/11/2016}
];


I expect this result:

Array = [
{score: 300, date: 11/11/2016},
{score: 200, date: 12/11/2016},
{score: 200, date: 11/11/2016}
];

Answer

Here you go,

You can further sort by date if the difference between the score equals 0.

You can simply subtract the date as below.

var highscores = [
  {score: 200, date: '11/11/2016'}, 
  {score: 300, date: '11/11/2016'}, 
  {score: 200, date: '12/11/2016'}
];

highscores.sort(function(a, b) {
  var c = b.score - a.score;
  return c === 0 ? new Date(b.date).getTime() - new Date(a.date).getTime() : c; // Even you can use without 'getTime' since the '-' operator implicitly do this
});

console.log(highscores);

Note: Date conversion inside the sort method is to make the sample to work. Instead actual object array should have the date object