In this lesson, the Riverside Book Club’s report went through every member and every book. You used one loop for the members and one inside it for each member’s books, totaled each member’s ratings, and collected the whole club’s books into one list, allBooks, which later parts of the report reuse.
Key Points
- Read the shape before you write the loops.
logis an array of members, so the outer loop goes through the members. Each member’sbooksis an array too, so the inner loop goes throughmember.books. - A member’s book count is already there, as
member.books.length. Together with a rating total, it gives an average later in the report. The rating total needs the inner loop, which adds each book’s rating to a running total. - A figure for each member starts at the top of the outer body, so each member starts fresh, and the outer body logs it after the inner loop finishes. Maya gets 4 books and 16 points, Jamal 12 points, and Dev, who gave up on Circe, 4.
- Luis has no books, so his inner loop runs zero times, and his total stays at
0. - Watch out: if the total starts above the outer loop, it never starts over, and each member’s figure includes everyone before them. Jamal then shows 28 points: Maya’s 16 plus his 12.
- A figure for the whole club starts above both loops.
allBooksis created once, and the inner body pushes each book onto it, so it holds all 15 books: four for Maya, then three, three, two and three, and none for Luis. allBooksholds the same book objects, not copies:allBooks[0] === log[0].books[0]istrue, so a change to that book shows up through either one.- A club-wide job can loop once over
allBooksor use the two loops overlog. Either way, its result starts above every loop it runs through. One loop overallBooks, with a check on the genre around the push, collects the six sci-fi books, and.map()turns them into their titles so the output stays short. Kindred and Project Hail Mary appear twice, because two members each have their own record of each book. - The highest-rated book is found across both levels, with the two loops over
log. The best so far starts above both loops asnull, meaning no book yet. In the inner body, a book replaces it ifbestis stillnullor if its rating is higher, so the first book found becomes the best even if the first member read nothing. - The answer is Kindred, rated 5. Four other books are rated 5 too, but none is higher, so Kindred stays. The club has books, so
bestisn’tnullby the end.
Final Code
The script report.js holds the club’s full log from the previous lesson. Below it, in place of the two path lines, are the four jobs from the video. The video showed each job on its own, but here they sit one after another in one file, so one run prints every result. The sci-fi job needs allBooks, so it comes after the loop that builds it, and the highest-rated job goes back to the two loops over log. Copy it to follow along: