import { Component, OnInit } from
"@angular/core"
;
import { Sort } from
"@angular/material/sort"
;
export interface Student {
physics: number;
maths: number;
chemistry: number;
name: string;
roll_number: number;
}
@Component({
selector:
"app-sort-overview-example"
,
templateUrl:
"sort-overview-example.component.html"
,
styleUrls: [
"./sort-overview-example.component.css"
],
})
export class SortOverviewExampleComponent implements OnInit {
ngOnInit(): void {}
school: Student[] = [
{ name:
"Niall"
, physics: 91, chemistry: 86, maths: 84, roll_number: 4 },
{ name:
"Liam"
, physics: 73, chemistry: 71, maths: 89, roll_number: 2 },
{ name:
"Zayn"
, physics: 74, chemistry: 91, maths: 99, roll_number: 5 },
{ name:
"Harry"
, physics: 82, chemistry: 80, maths: 92, roll_number: 3 },
{ name:
"Louis"
, physics: 96, chemistry: 76, maths: 93, roll_number: 1 },
];
sortedData: Student[];
constructor() {
this
.sortedData =
this
.school.slice();
}
sortData(sort: Sort) {
const data =
this
.school.slice();
if
(!sort.active || sort.direction ===
""
) {
this
.sortedData = data;
return
;
}
this
.sortedData = data.sort((a, b) => {
const isAsc = sort.direction ===
"asc"
;
switch
(sort.active) {
case
"name"
:
return
compare(a.name, b.name, isAsc);
case
"roll_number"
:
return
compare(a.roll_number, b.roll_number, isAsc);
case
"maths"
:
return
compare(a.maths, b.maths, isAsc);
case
"physics"
:
return
compare(a.physics, b.physics, isAsc);
case
"chemistry"
:
return
compare(a.chemistry, b.chemistry, isAsc);
default
:
return
0;
}
});
}
}
function
compare(a: number | string, b: number | string, isAsc: boolean) {
return
(a < b ? -1 : 1) * (isAsc ? 1 : -1);
}