Search code examples
javascriptarraysnestedjavascript-objects

How to sort a array of objects by nested object property stored at index?


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


Solution

  • 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));