Sort Function not working

asher14
Tera Contributor

My sort function is not working. My client controller my code is below. My HTML code is below.

I would like the dates and time field which is u_departure_date to display in ascending order and right now it is displaying the date and time as descending order.

 

HTML:

<td>{{row.u_departure_date}}</td>

 

Client Controller:

c.report.sort(function(a,b){
var a = $filter('emDate')(a.departure_date).getTime();
var b = $filter('emDate')(b.departure_date).getTime();
if(!b || a < b){
return 1;
}
if(!a || a > b){
return -1;
}
return 0;
});

1 ACCEPTED SOLUTION

Riya Verma
Kilo Sage
Kilo Sage

Hi @asher14 ,

 

Hope you are doing great.

 

To fix the sort function and display the u_departure_date field in ascending order, you need to make a small modification to the client controller code. You should change the return values for the comparison in the sort function

 

c.report.sort(function(a, b) {
  var aTime = new Date(a.u_departure_date).getTime();
  var bTime = new Date(b.u_departure_date).getTime();
  
  if (!bTime || aTime < bTime) {
    return -1; // Change from 1 to -1
  }
  if (!aTime || aTime > bTime) {
    return 1; // Change from -1 to 1
  }
  return 0;
});

 

 
Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.
Regards,
Riya Verma

View solution in original post

1 REPLY 1

Riya Verma
Kilo Sage
Kilo Sage

Hi @asher14 ,

 

Hope you are doing great.

 

To fix the sort function and display the u_departure_date field in ascending order, you need to make a small modification to the client controller code. You should change the return values for the comparison in the sort function

 

c.report.sort(function(a, b) {
  var aTime = new Date(a.u_departure_date).getTime();
  var bTime = new Date(b.u_departure_date).getTime();
  
  if (!bTime || aTime < bTime) {
    return -1; // Change from 1 to -1
  }
  if (!aTime || aTime > bTime) {
    return 1; // Change from -1 to 1
  }
  return 0;
});

 

 
Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.
Regards,
Riya Verma