In the last lesson, you went through every member’s books with one loop inside another and collected the whole club’s reading into allBooks. The log answers questions about books. The club’s organizer also kept a second record, one that a year-end report could draw on. It’s a sheet with one row per member and one column per quarter, recording how many books each member finished in that quarter.
Data like this, rows of numbers with no names inside, is common, and it needs a different kind of loop. In this lesson, you’ll read any cell of the sheet, total it by row and by column, and build an empty sheet for next year. Start with the shape, and then find out how many books Rosa finished in the second quarter.
Read a Cell, Row First
A sheet of numbers has no property names to use, so the path to a value has to be made of positions. In JavaScript, you store it as an array of rows, where each row is itself an array. An array of arrays used like this is called a grid. The first index picks a row, and the second picks a column within that row.
Create quarters.js with the club’s sheet. The rows follow the members in the same order as the log, so names holds their names to label the rows:
quarters.js
const names = ["Maya", "Jamal", "Rosa", "Dev", "Hannah", "Luis"];
const quarterCounts = [
[1, 0, 1, 2],
[1, 1, 1, 0],
[0, 2, 0, 1],
[0, 0, 0, 1],
[2, 0, 0, 1],
[0, 0, 0, 0],
];
console.log(quarterCounts[2]);
console.log(quarterCounts[2][1]);
Each row has four numbers, for January to March, April to June, July to September, and October to December. Luis joined in December and hasn’t finished a book yet, so his row is all zeros. Run the script:
$ node quarters.js
[ 0, 2, 0, 1 ]
2
The first line shows that quarterCounts[2] on its own is a whole row, Rosa’s, because she’s the third member. The second line goes one step further. Read quarterCounts[2][1] aloud as “row 2, then item 1 of that row,” and you get Rosa’s book count for the second quarter, 2. Each pair of brackets accesses the next level, just as log[1].books[0] did in the log.
Watch out: if you’re used to spreadsheets, you might write quarterCounts[2, 1] for row 2, column 1. JavaScript reads 2, 1 with the comma operator, which keeps only the last number. So you get Jamal’s whole row, quarterCounts[1], and no error.