sample JSON:
[{ 'student': 'A',
'std': [ { 'cls': 3, 'date': '26/12/2022', 'flag': true },
{ 'cls': 2, 'date': '16/11/2021' 'flag': true },
{ 'cls': 1, 'date': '25/11/2020', 'flag': false }]
},
{ 'student': 'B',
'std': [ {'cls': 3, 'date': '26/12/2022', 'flag': false},
{'cls': 2, 'date': '16/11/2021', 'flag': true },
{'cls': 1, 'date': '25/11/2020', 'flag': false}]
}]
I have create table using above kind of JSON, as below:
<tbody>
<ng-container *ngFor="let s of student">
<tr *ngFor="let std of s.std" >
<td> {{s.student}} </td>
<td > {{std.cls}} </td>
<td > {{std.date}} </td>
<td > {{std.flag}} </td>
</tr>
</ng-container>
my question is how can I sort the table using date column (from recent to old) also with flags (true on top false on bottom) in Angular.
Desire Output:
student cls date flag
A 3 26/12/2022 true
A 2 16/11/2021 true
B 2 16/11/2021 true
B 3 26/12/2022 false
A 1 25/11/2020 false
B 1 25/11/2020 false
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>