Open In App

Sort an array of objects in typescript?

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We can achieve the sorting in TypeScript using the sort() function which is an inbuilt TypeScript function that is used to sort the elements of an array.

Below are a few examples showing the sorting in TypeScript.

Example 1: In this example, we will learn how to use the sort function to sort the array of objects based on object properties.

Javascript




const course = [
    { name: "HTML", cost: 30 },
    { name: "CSS", cost: 25 },
    { name: "Typescript", cost: 35 },
];
console.log("Before Sorting");
console.log(course);
course.sort((a, b) => a.cost - b.cost);
console.log("After Sorting");
console.log(course);


Output:

z151

Example 2: This example defines an interface Student, creates an array of Student objects, and then demonstrates how to sort them by name and ID in both ascending and descending orders using the sort method. It’s essential to use the slice method to create a copy of the array before sorting to avoid modifying the original array.

Javascript




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 },
];
 
// Sort by name in ascending order
const studentsByNameAscending =
    students.slice()
        .sort((a, b) =>
            a.name.localeCompare(b.name));
 
// Sort by name in descending order
const studentsByNameDescending =
    students.slice()
        .sort((a, b) =>
            b.name.localeCompare(a.name));
 
// Sort by ID in ascending order
const studentsByIdAscending =
    students.slice()
        .sort((a, b) =>
            a.id - b.id);
 
// Sort by ID in descending order
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);


Output:

z152



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads