Boss lesson · Unit 04
A gradebook
An array of typed records: averages, the best, groups, a ranking
What you practise
- An array of typed records: averages, the best student, grouping by grade with a
Record, a sorted report
Try a question from this lesson
Pick one
A gradebook is an array of objects, one per student. What does this print?
const book = [
{ name: "Ada", score: 90 },
{ name: "Bo", score: 60 },
];
console.log(book[1].name);Correct answer
Bo
Why
book[1] is the second object, because indexes start at 0, and .name reads its name. An index picks the record, a dot picks the property. Nearly all real data is shaped like this: a list of records.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A lookup table
An object can serve as a table that you look things up in. Its type is written Record<string, number>: the names are strings and the values are numbers.
When the name is held in a variable, use square brackets with the variable in them, in place of the dot.
It is the natural tool for counting things by name.
const counts: Record<string, number> = {
A: 0,
B: 0,
};
counts["A"] += 1;
const key = "B";
counts[key] += 2;
console.log(counts.A, counts.B); // 1 2Concept
Sorting records
sort puts an array in order. It reorders the array itself: no copy is made.
You hand it a function that compares two items, a and b. A negative result means a goes first.
So a.score - b.score sorts from lowest to highest, and b.score - a.score from highest to lowest.
const book = [
{ name: "Ada", score: 75 },
{ name: "Bo", score: 90 },
];
book.sort((a, b) => b.score - a.score);
console.log(book[0].name); // Bo10 more exercises in the app
- 4× type the answer
- 1× order the lines
- 2× fill the blanks
- 2× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.