How to sort custom objects in Type Script

Imagine you have a student class and you need to sort it reverse order of marks field to calculate ranks of students in the class.

class Student{
    name:String
    marks:Number
    constructor(name:string, marks:number) {
        this.name = name
        this.marks = marks
    }
}

Student objects as part of the array. 

var students:Array<Student> = [
    new Student("aseem",47),
    new Student("prem",97),
    new Student("john",100)

]

sort students by comparing them based on marks field. 

console.log(students.sort( (a,b)=> a.marks > b.marks ? -1:1 ))

here, we used the arrow function which takes a and b objects as params, then we used the ternary operator to compare marks and return the number as -1 or 1 as the result of comparison. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.