Problem overview
JavaScript can sort numbers and strings because it knows how to order them. For objects of your own class it doesn't, until you say how two of them compare. You write a class Student, created by Student(name, grade), with a method compareTo(other), and a method rankStudents(students) in Solution that sorts the students with the array's own sort and returns their names in that order.
The ranking rule: a higher grade comes first. When two grades are equal, the name that comes first alphabetically comes first. For Ana (90), Bob (85) and Cid (90), the answer is Ana Cid Bob: Ana and Cid tie at 90, and Ana's name comes before Cid's.
Approach: put the rule in the class
TypeScript has no interface that sort looks for. The convention is a method compareTo(other) that returns a negative number when this student comes first, a positive number when other comes first, and 0 when they are equal. Array.prototype.sort asks for exactly that kind of answer from a comparison function: negative means the first argument goes first. So rankStudents passes a small function that hands the work to compareTo. The rule lives in the class, and no sorting loop is written.
The sort makes O(n log n) comparisons for n students, and each comparison takes constant time.
Step by step
- Fields. Declare
name: stringandgrade: numberinStudent. They stay public becauserankStudentsreads each name. - Constructor. Store both parameters in
this.nameandthis.grade. - Grades first. If the grades differ, return
other.grade - this.grade. A higher grade must rank first, so whenthishas the bigger grade the result is negative. - Names second. With equal grades, return
this.name.localeCompare(other.name). It is negative whenthis.namecomes first alphabetically, so students with the same grade go from A to Z. - Sort. Call
students.sortwith a function offirstandsecondthat returnsfirst.compareTo(second). - Collect the names. Make an empty
string[]withconst, loop over the sorted students withfor...of, push eachstudent.nameand return the array.
The solution in TypeScript
class Student {
name: string;
grade: number;
constructor(name: string, grade: number) {
this.name = name;
this.grade = grade;
}
compareTo(other: Student): number {
if (this.grade !== other.grade) {
return other.grade - this.grade;
}
return this.name.localeCompare(other.name);
}
}
class Solution {
rankStudents(students: Student[]): string[] {
students.sort((first, second) => first.compareTo(second));
const names: string[] = [];
for (const student of students) {
names.push(student.name);
}
return names;
}
}
TypeScript details worth knowing:
sortchanges the array in place. It also returns the same array. AfterrankStudentsruns, the list you passed in is in ranked order too. To keep the original order, sort a copy:[...students].sort(...).sortwith no comparison is not enough. Without a function,sortturns elements into strings and compares those. For numbers that gives[10, 9, 1].sort()equal to[1, 10, 9]. ForStudentobjects, every string is[object Object], so nothing moves.- The comparison function is a rule, not a boolean. It returns a number: negative, zero or positive. Returning
trueorfalsedoesn't say which of three outcomes applies. - Subtracting works for grades. Grades are whole numbers from 0 to 100, so
other.grade - this.gradeis a safe, exact difference. For strings you can't subtract, which is why names uselocaleCompare. localeComparereturns a number. It is negative, zero or positive, and"Ann".localeCompare("Anna")is negative: when one name is the start of the other, the shorter comes first.
Seeing it run
const s = new Solution();
const mk = (xs: [string, number][]) => xs.map(([n, g]) => new Student(n, g));
console.log(s.rankStudents(mk([["Ana", 90], ["Bob", 85], ["Cid", 90]])).join(" "));
console.log(s.rankStudents(mk([["Eve", 55], ["Dan", 100], ["Bea", 0], ["Cal", 99]])).join(" "));
console.log(s.rankStudents(mk([["Max", 88], ["Leo", 88], ["Anna", 88], ["Ann", 88]])).join(" "));
console.log(new Student("Ana", 90).compareTo(new Student("Bob", 85)));
console.log(new Student("Bob", 85).compareTo(new Student("Ana", 90)));
console.log(new Student("Ana", 90).compareTo(new Student("Ana", 90)));
Ana Cid Bob
Dan Cal Eve Bea
Ann Anna Leo Max
-5
5
0
In the second list all the grades differ, so only the grades decide, from 100 down to 0. In the third list everyone has 88, so the names decide, and Ann comes before Anna. The last three lines call compareTo directly: Ana against Bob is -5 because Ana's 90 beats Bob's 85, the reverse is 5, and two equal students give 0.
The sort is only as good as compareTo. The lesson's tests also call your comparison directly on each pair of neighbours in the ranked list, so the method has to be right on its own, not just good enough to produce the right order for the examples.
Edge cases and common mistakes
- Reversed subtraction.
this.grade - other.graderanks the lowest grade first. The higher grade must give a negative result, so it isother.grade - this.grade. - Ignoring ties. Without the name rule, students with equal grades stay in whatever order they started in. Example 1 depends on Ana coming before Cid.
- Comparing names with
-. Subtracting strings givesNaN, not a useful order. UselocaleCompare. - Calling
sort()bare. It leaves the students where they are, as explained above. - Writing a sorting loop. The point of the lesson is that the class knows the rule and the language's sort does the sorting.
- A single student. A list of one is already sorted; the comparison is never called and the answer is that one name.
- Surprised caller. Because
sortreorders the input array, a caller that still needs the original order should pass a copy.
