Home > Mobile >  Sort table by date column without mat
Sort table by date column without mat

Time:12-20

sample JSON:

[{'student': 'A', 'std':[{'cls':3, 'date':'26/12/2022'},{'cls':2, 'date':'16/11/2021'},{'cls':1, 'date':'25/11/2020'}]},{'student': 'B', 'std':[{'cls':3, 'date':'26/12/2022'},{'cls':2, 'date':'16/11/2021'},{'cls':1, 'date':'25/11/2020'}]}]

I have create table using above kind of JSON, my question is how can I sort the table using date column in Angular.

CodePudding user response:

Let's set it as a variable:

let data = [{'student': 'A', 'std':[{'cls':3, 'date':'26/12/2022'}....

Now you can do a sort function like so (Generic example):

data.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});

For your case, I guess you want to sort by std, so it will look like this:

data.sort(function(a,b){
  // Find the earliest date in the array std for b and a
  const aDate = a.std.sort((a1,b1)=>{
    return new Date(a1.date) - new Date(b1.date)
  })[0]
  const bDate = a.std.sort((a1,b1)=>{
    return new Date(a1.date) - new Date(b1.date)
  })[0] 
  return new Date(bDate.date) - new Date(aDate.date);
});

CodePudding user response:

  • try use ng-repeat and pileline to create order date in table:
<tr ng-repeat="student in students | orderBy: sortByDate"> // ASC order
  <td>{{ student.student }}</td>
  <td>{{ student.std.cls }}</td>
  <td>{{ student.std.date }}</td>
</tr>
  • Related