0

I need to sort this array of objects by its nested property in descending order but the property that I need to sort by is "stored" inside an property index (not sure if thats what's called). How do i do this with .sort()?

Ive tried searching for the answer on stackoverflow and there are alot of topics on this but I can't find this specific answer or I can't understand it..

I have tried this code:

        var array = [
          {user:"Julia", startTime: "2019-04-09T11:22:36"}, 
          {user:"Lisa", startTime:"2019-04-10T11:22:36"},
          {user:"Hank", startTime:"2019-04-11T11:22:36"},
          {user:"Hank", startTime:"2019-04-08T11:22:36"},
        ];
        
        
        function compare(a, b) {
          const startA = new Date(a.startTime).getTime();
          const startB = new Date(b.startTime).getTime();
          return startA + startB;
        }
        
        console.log(array.sort(compare));
Kulio
  • 145
  • 1
  • 10

3 Answers3

2

return startB - startA; instead of return startA + startB;.

mbojko
  • 13,503
  • 1
  • 16
  • 26
0

You were close: just change return startA + startB; to return startA > startB ? -1 : 1;

var array = [
  {user:"Julia", startTime: "2019-04-09T11:22:36"}, 
  {user:"Lisa", startTime:"2019-04-10T11:22:36"},
  {user:"Hank", startTime:"2019-04-11T11:22:36"},
  {user:"Hank", startTime:"2019-04-08T11:22:36"},

];

function compare(a, b) {
  const startA = new Date(a.startTime).getTime();
  const startB = new Date(b.startTime).getTime();
  return startA > startB ? -1 : 1;
}

console.log(array.sort(compare));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
topheman
  • 7,422
  • 4
  • 24
  • 33
0

Aprreciate @mbojko's answer since User wants to sort array in desecnding order use startB - startA;

On sorting dates in decending order - most recent dates come first

var array = [
   {user:"Julia", startTime: "2019-04-09T11:22:36"}, 
   {user:"Charles", startTime:"2019-04-10T11:22:36"},
   {user:"Lisa", startTime:"2019-04-10T11:22:36"},
   {user:"Hank", startTime:"2019-04-11T11:22:36"},
   {user:"Hank", startTime:"2019-04-08T11:22:36"},

];

function compare(a, b) {

const startA = new Date(a.startTime).getTime();
const startB = new Date(b.startTime).getTime();
return startB - startA;
}

console.log(array.sort(compare));