Problem overview
In version 5 of the Report Card project the scores are no longer in a list. They sit in an object that maps each subject name to a score: grades, typed Record<string, number>. The program prints each subject with its letter grade, one per line, in alphabetical order of the subject names.
The scale is unchanged: 90 or more is an A, 80 to 89 a B, 70 to 79 a C, 60 to 69 a D, and anything lower an F. The starting object lists Math, English, Science and History, in that order, but the output is sorted by name:
English: C
History: D
Math: A
Science: B
Approach: sort the keys, then look each one up
An object doesn't give you "the n-th entry" by position, so the loop can't count positions as it did over arrays. The program works with the names instead. Object.keys(grades) returns an array of the object's keys, ["Math", "English", "Science", "History"], in the order they were written. Calling .sort() on that array puts the names in alphabetical order. The program then visits each name and uses it as a key to read its score.
Sorting the names, not the object, is the point: an object's order isn't something to rely on for output. For string keys it is the order of insertion, but keys that look like integers jump to the front in ascending order. For example, Object.keys on {"b": 1, "10": 2, "a": 3, "2": 4} gives ["2", "10", "b", "a"]. Sorting the key array makes the order explicit.
Inside the loop, each pass does what version 4 did: read the score, run the grading ladder, print one line. Only the source of the score changes, from scores[i] to grades[subject].
For the starting data, the sorted array is ["English", "History", "Math", "Science"]. The loop reads grades["English"] first, which is 78, so the first line is a C. Then it reads History (67, a D), Math (92, an A) and Science (85, a B).
The result is the same four lines as the expected output, because the order of the lines comes only from the order of the sorted names. The object's own order, which puts Math first, plays no part once the keys are sorted.
Step by step
- Get the sorted names. Create
subjectsas aconstof typestring[], holdingObject.keys(grades).sort(). The array fromObject.keysis new, so sorting it doesn't touch the object. - Loop over the names.
for (const subject of subjects)hands out one name per pass, in the sorted order. Write the closing brace right away. - Look up the score. Inside the loop, store
grades[subject]in aconstnamedscore, typednumber. The name is the key, and the value stored under it is that subject's score. - Declare the grade. A
letnamedgrade, typedstring, with no value yet. - Start the ladder with
if (score >= 90)for"A". The top grade is checked first, so later tests only need a lower bound. - Add
else if (score >= 80)for"B". - Add
else if (score >= 70)for"C". - Add
else if (score >= 60)for"D". - Close with
elsefor"F", then close the chain. - Print the line inside the loop, after the chain:
subject,": "andgrade, joined with+. It runs once per subject.
The solution in TypeScript
const grades: Record<string, number> = {"Math": 92, "English": 78, "Science": 85, "History": 67};
const subjects: string[] = Object.keys(grades).sort();
for (const subject of subjects) {
const score: number = grades[subject];
let grade: string;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
console.log(subject + ": " + grade);
}
Details worth knowing:
Record<string, number>. This type says "an object whose keys are strings and whose values are numbers". It is erased when the code compiles to JavaScript, wheregradesis an ordinary object.for...ofandfor...indiffer.for (const subject of subjects)loops over the values of an array.for (const k in grades)loops over an object's keys, but in the object's own order, not alphabetical. For the starting data it visits Math, English, Science and History.- Default
sort()compares as text. With no comparator it orders strings by their character codes, which is fine for names but trips on numbers:[10, 9, 100, 1].sort()gives[1, 10, 100, 9]. Sorting numbers needs(x, y) => x - y. sort()changes the array it is called on and returns that same array. Here it runs on the fresh array fromObject.keys, so nothing else is affected.
Edge cases and common mistakes
- Capital letters sort before lowercase ones. The default sort compares character codes, and every capital letter has a smaller code than every lowercase one.
["Math", "english", "Art", "science"].sort()gives["Art", "Math", "english", "science"]. With subjects namedMath,English,scienceandArt, the lowercase one comes last. The lesson's subjects all start with a capital, so the plainsort()is enough. - Forgetting to sort. Without
.sort()the loop follows the object's order and prints Math, English, Science, History. - A missing key.
grades["Art"]for a subject that isn't in the object givesundefined, not an error. Looping overObject.keysavoids this, because every key it returns exists. - Boundaries. With Math 59, English 60, Art 80 and science 90, the output is
Art: B,English: D,Math: Fandscience: A. The score 60 is a D and 59 an F. - An empty object.
Object.keys({})is an empty array, so the loop never runs and nothing is printed.
Testing
- The starting object prints
English: C,History: D,Math: AandScience: B. - An object with
"Math": 59, "English": 60, "science": 90, "Art": 80printsArt: B,English: D,Math: Fandscience: A.
