Source: Activity Guide – Traversals Make, Code.org CSP
Tags: traversal, list filter pattern, filtering multiple lists, appendItem, for loop, getColumn, onEvent, Code.org, App Lab, CSP, Computer Science Principles
Difficulty: Intermediate Prerequisites: Unit 6 Lessons 1–11 (list basics, indexing, for loops, traversals). You should already be comfortable creating lists, accessing elements by index, and writing basic for loops before tackling this material.
This lesson pulls together everything from Unit 6 into a single working app: a "Random Forecaster" that reads from a data table, filters rows by a condition, and displays the result on screen. It is the first time in the course you will filter multiple parallel lists at once using a single traversal, then use those filtered lists to drive what the user sees. If you have been treating lists as isolated containers up to now, this is where you learn to think of them as synchronised columns in a table, filtered and read together by index.
You traverse one list to decide which rows to keep, then append the matching elements from every parallel list into new filtered lists. A separate function picks a random index from the filtered lists and updates the screen. The whole thing is wired to a button through onEvent().
Traversal
Visiting every element in a list, one at a time, usually with a for loop. In simple terms, it means walking through the entire list from start to finish so you can inspect or act on each item.
List filter pattern
A code pattern where you loop through a list, check a condition on each element, and append only the elements that pass into a new (filtered) list. Think of it as a sieve: everything goes in, only the matching items come out.
Filtering multiple lists
An extension of the list filter pattern where you check the condition on one list but append from several parallel lists at the same index. In simple terms, if row 4 passes the test, you grab element 4 from every list, not just the one you tested.
Parallel lists
Two or more lists where element i in each list describes the same entity (the same row in a table). Think of it as columns in a spreadsheet: cityList[3], conditionList[3], and highTempList[3] all describe the same forecast entry.
getColumn(table, column)
A Code.org App Lab function that pulls an entire column from a data table and returns it as a list. This is how you load your parallel lists at the start of the program.
appendItem(list, item)
Adds an item to the end of a list. Used inside the filter function to build up filtered lists one matching element at a time.
onEvent(id, type, callback)
Registers an event handler in App Lab. When the user interacts with the element matching id (for example, clicking a button), the callback function runs. This is what connects the "Get Forecast" button to your filter-and-display logic.
The app uses a "Daily Weather" table with six columns. Each column becomes a list in your program via getColumn():
cityList – the city name for each forecast entry
forecastNumberList – how many days from today (1 = today, 2 = tomorrow, and so on)
conditionList – weather condition (e.g. "moderate rain", "sunny")
highTempList – the high temperature
lowTempList – the low temperature
iconList – a weather icon identifier
All six lists are parallel: index 0 in every list describes the same forecast row.
The goal is to keep only the rows where forecastNumberList[i] equals 2 (tomorrow's forecast). The filter function does four things:
Resets all five filtered lists to empty arrays. This matters because the function may be called more than once, and you do not want stale data carried forward.
Loops through forecastNumberList using a standard for loop: for (var i = 0; i < forecastNumberList.length; i++).
Inside the loop, checks whether forecastNumberList[i] == 2.
If the condition is true, appends the element at index i from each of the other five lists into the corresponding filtered list.
After the loop finishes you have five filtered lists that contain only tomorrow's forecast data, all still synchronised by index.
A second function handles output:
Generates a random index within the range of the filtered lists (e.g. Math.floor(Math.random() * filteredCityList.length)).
Uses that single random index to pull the city name, condition, high temp, low temp, and icon from the five filtered lists.
Updates the screen elements ("cityOutput", "highTempOutput", "lowTempOutput", "conditionOutput", "iconOutput") with the corresponding values.
Because the filtered lists are parallel, one random index is enough to grab a complete, coherent forecast.
An onEvent() on the "Get Forecast" button calls the filter function and then the display function (or calls a single function that does both). Every click re-filters and picks a new random city.
// 1. Load lists from table
var cityList = getColumn("Daily Weather", "City");
// ... repeat for all six columns
// 2. Create empty filtered lists
var filteredCityList = [];
// ... repeat for all five filtered lists
// 3. Filter function
function filter() {
filteredCityList = [];
// ... reset all filtered lists
for (var i = 0; i < forecastNumberList.length; i++) {
if (forecastNumberList[i] == 2) {
appendItem(filteredCityList, cityList[i]);
// ... append from each parallel list
}
}
}
// 4. Display function
function updateScreen() {
var index = Math.floor(Math.random() * filteredCityList.length);
setText("cityOutput", filteredCityList[index]);
// ... set text for each output element
}
// 5. Event handler
onEvent("forecastButton", "click", function() {
filter();
updateScreen();
});
Random index within a filtered list: var index = Math.floor(Math.random() * filteredCityList.length);
Loading a column into a list: var cityList = getColumn("Daily Weather", "City");
Basic filter condition: if (forecastNumberList[i] == 2) { ... }
This pattern is how almost any data-driven app works behind the scenes. When a shopping site lets you filter by "in stock" and "under £50", it is traversing a product table and building filtered lists from every column at once, exactly as you do here. The parallel-list approach also mirrors how databases handle SELECT queries with WHERE clauses.
Students often forget to reset the filtered lists to empty arrays at the start of the filter function. Without the reset, clicking "Get Forecast" a second time appends new results onto the old ones, doubling the data.
Students sometimes use a different index variable for each list inside the filter loop. You need the same i across all lists, because the lists are parallel and the match was found at position i.
Students occasionally filter the wrong list. You traverse the list that contains the value you are checking (e.g. forecastNumberList), not one of the output lists like cityList.
Students sometimes confuse appendItem with insertItem. appendItem adds to the end, which is what you want when building a filtered list from scratch. insertItem places an element at a specific index and shifts everything after it.
⚠️ The list filter pattern is a commonly tested concept on the AP CSP exam. You should be able to trace through a filter loop and predict which elements end up in the filtered list.
⚠️ Parallel list traversal (using one index across multiple lists) appears frequently in AP CSP multiple-choice questions. Expect questions that ask what value is at a given index after filtering.
⚠️ Understanding when and why to reset filtered lists is a detail examiners use to test whether you truly understand the pattern or just memorised it.
True or false: When filtering multiple parallel lists, you need a separate for loop for each list.
A: False. One for loop traverses the "key" list, and inside that single loop you append from all parallel lists at the same index.
Fill in the blank: Before the for loop in a filter function, you should ______ all filtered lists.
A: Reset them to empty arrays.
True or false: getColumn() returns a single value from a table.
A: False. It returns an entire column as a list.
Fill in the blank: To add an element to the end of a list in App Lab, use the ______ function.
A: appendItem()
True or false: The random index used to pick a city should be generated from the length of the original (unfiltered) list.
A: False. It should use the length of the filtered list, because the filtered list may be shorter.
Q: You have three parallel lists: nameList, gradeList, and ageList. Write pseudocode to filter for all students with a grade of 11 and store the results in filteredNameList, filteredGradeList, and filteredAgeList.
A: Reset all three filtered lists to empty. Loop i from 0 to gradeList.length - 1. If gradeList[i] == 11, append nameList[i] to filteredNameList, gradeList[i] to filteredGradeList, and ageList[i] to filteredAgeList.
Q: Why must all parallel lists be the same length?
A: Because the lists represent columns of the same table. Index i must refer to the same row across every list. If one list is shorter, accessing index i could go out of bounds or pull data from the wrong row.
Q: A student's filter function works correctly the first time the button is clicked, but on the second click the filtered lists contain duplicate entries. What is the most likely bug?
A: The filtered lists are not being reset to empty arrays at the start of the filter function, so new results are appended onto the previous results.
Q: After filtering, filteredCityList has 8 elements. What range of values could a valid random index take?
A: 0 through 7 (integers), because list indices in JavaScript and App Lab are zero-based.
Q: In the Random Forecaster app, which list do you traverse to decide whether a row should be kept?
A: forecastNumberList, because the filtering condition checks whether the forecast number equals 2 (tomorrow).
This connects directly to the broader concept of data abstraction in CSP: tables are abstracted into parallel lists, and filtering is a form of data processing that reduces a dataset to only the relevant entries. It also lays the groundwork for understanding how real databases use queries, and it reinforces the traversal patterns from earlier in Unit 6 by applying them to a multi-list context.
list traversal, list filter pattern, filtering multiple lists, parallel lists, parallel arrays, appendItem, getColumn, onEvent, for loop filtering, App Lab, Code.org, CSP Unit 6, AP Computer Science Principles, random index, data table traversal, weather app project, filtered list reset, traversal pattern