interface Student {
name: string;
id: number;
}
const students: Student[] = [
{ name:
"Ram"
, id: 102 },
{ name:
"Shyam"
, id: 105 },
{ name:
"Aman"
, id: 103 },
{ name:
"Shri"
, id: 101 },
];
const studentsByNameAscending =
students.slice()
.sort((a, b) =>
a.name.localeCompare(b.name));
const studentsByNameDescending =
students.slice()
.sort((a, b) =>
b.name.localeCompare(a.name));
const studentsByIdAscending =
students.slice()
.sort((a, b) =>
a.id - b.id);
const studentsByIdDescending =
students.slice()
.sort((a, b) =>
b.id - a.id);
console
.log(
"Students sorted by name (ascending):"
,
studentsByNameAscending);
console
.log(
"Students sorted by name (descending):"
,
studentsByNameDescending);
console
.log(
"Students sorted by ID (ascending):"
,
studentsByIdAscending);
console
.log(
"Students sorted by ID (descending):"
,
studentsByIdDescending);