Lab 8: Farfetch’d
![]()
In this lab, you will use fetch() to read data from the PokéAPI and use JavaScript’s higher-order array methods (forEach(), map(), filter(), and reduce()) to build a small Pokémon party builder.
You should consult the following references as needed:
- The PokéAPI documentation
- MDN Array reference
- MDN Using the Fetch API
When you are done, you will be able to browse the original 151 Pokémon, filter them by name, pick up to six, and calculate your party’s total base stat total (BST).
(Fun fact: the lab is named after Farfetch’d, Pokémon #83.)
Starter Code
Download the following files to get started:
- index.html – An HTML page with Bootstrap.
- pokemon.js – A JavaScript file with comments.
You will modify and submit only the pokemon.js file.
Most of the UI is already built for you: the cards, selecting a 6 Pokémon team, and the event listeners are all provided.
Your job is to fill in the functions marked TODO, one part at a time.
Open index.html with a Live Preview. You should never open HTML files by double-clicking them anyway, because the browser will treat them as file:// URLs and block your fetch() requests.
Part 1: GET the Pokémon
Your first task is to retrieve the list of original (Generation 1) Pokémon, #1 through #151, and show them on the page.
-
Find the URL that lists Pokémon. You will not be told which URL to use, so you’ll need to find it by looking at the API documentation and experimenting with the “Try it now!” box on the home page.
The PokéAPI documentation can be tricky to read, so start with these parts of the page:
- Resource Lists/Pagination section: explains how the API returns lists of things (see the
limitparameter).- You’ll need to use a “query parameter” for
limit– what’s that? It’s the little?in the URL, followed bykey=valuepairs. For example, Google useshttps://www.google.com/search?q=helloto search for “hello”. The?q=hellopart is the query parameter.
- You’ll need to use a “query parameter” for
- The Home Page has a “Try it now!” box that lets you experiment with the API and see what data comes back.
- Try the
pokemonendpoint and see what it returns. Then try adding alimitquery parameter. - Check the “View raw JSON” checkbox to see the data formatted like how your code would receive it.
- Try the
Hint 1: I can’t find the right URL
By default, the API only returns 20 results at a time. The
limitsetting controls how many results the API returns in one request.To see how it works, go to the PokéAPI home page and find the “Try it now!” box. Enter
pokemon?limit=5and look at both the request that gets made and the data that comes back.Try a few different limits and watch how the
resultsarray changes. Which limit gives you exactly the original 151?Hint 2: Just give me the URL
Use
https://pokeapi.co/api/v2/pokemon?limit=151. - Resource Lists/Pagination section: explains how the API returns lists of things (see the
-
Fill in the
loadPokemon()function. It is already declaredasync, so you can useawait(recommended) or.then(). It should make the GET request and parse the response as JSON. The API’s list looks like this:{ count: ..., next: ..., previous: ..., results: [ { name: "bulbasaur", url: "https://pokeapi.co/api/v2/pokemon/1/" }, { name: "ivysaur", url: "https://pokeapi.co/api/v2/pokemon/2/" }, ... ] } -
Pass each Pokémon in the response’s
resultsarray to the providedaddPokemonCard()function. Each{name, url}object is what you pass in.You don’t need to build the cards yourself.
addPokemonCard(pokemon)saves the Pokémon in theallPokemonarray and adds its card (picture, number, name, and checkbox) to the page. It usessplit()on theurlto pull out the Pokémon’s id, such as4inhttps://pokeapi.co/api/v2/pokemon/4/.Hint: Using a loop to call a function on every item
You can call a function on every item of an array with either a
for...ofloop orforEach(). These two do the same thing:Use whichever one you’re more comfortable with.for (const item of items) { doSomething(item); } items.forEach(item => doSomething(item));
When this part works, you should see a scrollable list of 151 cards. You can check up to six of them.
Part 2: Filter the list
Next, make the filter box above the list work.
The provided code calls filterPokemon(allPokemon, queryText) every time the user types, and it displays whatever array you return.
-
Look at the two parameters your function receives:
allPokemonis an array of{name, url}objects, one per Pokémon.queryTextis a string containing what the user typed.
// allPokemon: [ { name: "bulbasaur", url: "https://pokeapi.co/api/v2/pokemon/1/" }, { name: "ivysaur", url: "https://pokeapi.co/api/v2/pokemon/2/" }, ... ] // One Pokémon from the array: { name: "charmander", url: "https://pokeapi.co/api/v2/pokemon/4/" } -
Implement
filterPokemon()to usefilter()and return a new array with only the Pokémon whosenamecontainsqueryText.Hint: How does filter() work?
filter()calls a function on every item of an array. It returns a new array with only the items for which the function returnedtrue.const numbers = [3, 8, 12, 5]; const bigOnes = numbers.filter(n => n > 4); // [8, 12, 5] -
Make the search ignore upper/lower case and any spaces around the text.
Hint: Useful string methods
You’ll want the string methods
includes(),toLowerCase(), andtrim().
filterPokemon() MUST use filter().
For example, typing char should leave only Charmander, Charmeleon, and Charizard.
Clearing the box should bring back all 151 Pokémon.
Part 3: Total party BST
A Pokémon’s base stat total (BST) is the sum of its six base stats (HP, Attack, Defense, Special Attack, Special Defense, and Speed). For example, Farfetch’d has stats of 52, 90, 55, 58, 62, and 60, so its BST is 377.
When the user clicks “Calculate total party BST”, the provided code does this:
- It calls
getParty()to get the checked Pokémon as an array of{name, url}objects. - It passes that array to your
getPokemonData()function. - It passes the result to your
calculateBST()function. - It displays each Pokémon’s BST and the party total.
Your job is to write the two functions in the middle:
flowchart LR
A[" "] -- "[{name, url}, ...]" --> B["getPokemonData"]
B -- "[{id, name, stats, ...}, ...]" --> C["calculateBST"]
C -- "total BST (a number)" --> D[" "]
style A fill:none,stroke:none
style D fill:none,stroke:none
You’ll want to reference the PokéAPI documentation to see what the data looks like. Go to the Pokémon > Pokemon section: it describes the pokemon endpoint. You can use it to get information about a single Pokémon.
-
Look at the data you will be working with. Each
urlin the party list is the endpoint for that one Pokémon, so try opening one in your browser to see what you get back. The data for one Pokémon looks something like this (with many more fields that you can ignore):{ id: 83, name: "farfetchd", stats: [ { base_stat: 52, stat: { name: "hp" } }, { base_stat: 90, stat: { name: "attack" } }, ... ], ... } -
Write
getPokemonData(pokemonList). It takes an array of{name, url}objects and returns an array of the full data for each one, in the same order. The function is already declaredasync, so you can useawait(recommended) or.then(). You can fetch the Pokémon one at a time using a loop, or you can usemap()to build the array.- Example: if the input is
[{name: "bulbasaur", url: "https://pokeapi.co/api/v2/pokemon/1/"}], the output should be[{id: 1, name: "bulbasaur", stats: [...], etc.}]. (The whole data object from the API call from the step above, not just the name and url.)
Want faster performance? Make concurrent requests!
If you
awaiteach request inside a loop, every request waits for the previous one to finish. Instead, you can start all the requests at once and wait for all of them to finish withPromise.all(). It takes an array of promises and gives you back an array of their results, in the same order.// urls is an array of strings const promises = urls.map(url => fetch(url).then(response => response.json())); const results = await Promise.all(promises); - Example: if the input is
-
Write
calculateBST(pokemonData). It takes the array of full data objects (the output ofgetPokemonData) and returns the party’s total BST as a single number.We have already provided
getBST(pokemon), which returns the BST of one Pokémon’s data object. The page uses it to show each Pokémon’s BST. Your task is to figure out how to combine them into one total.
In calculateBST(), do NOT use any form of loop (such as a for loop) or forEach(), and you MUST use reduce().
The purpose is to work with the array methods.
Also, calculateBST() is a regular function (not async) that returns the total as a number.
The autograder checks for the requirements above, and code that breaks them will not receive credit for the affected tests.
Submission
When you are finished, submit pokemon.js to Gradescope.
The autograder checks your code with a simulated version of the API, so your results will not depend on the network.