Skip to content

Lab 8: Farfetch’d

Farfetch'd, a duck Pokémon holding a leek

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:

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:

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.

  1. 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 limit parameter).
      • You’ll need to use a “query parameter” for limit – what’s that? It’s the little ? in the URL, followed by key=value pairs. For example, Google uses https://www.google.com/search?q=hello to search for “hello”. The ?q=hello part is the query parameter.
    • The Home Page has a “Try it now!” box that lets you experiment with the API and see what data comes back.
      • Try the pokemon endpoint and see what it returns. Then try adding a limit query parameter.
      • Check the “View raw JSON” checkbox to see the data formatted like how your code would receive it.
    Hint 1: I can’t find the right URL

    By default, the API only returns 20 results at a time. The limit setting 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=5 and look at both the request that gets made and the data that comes back.

    Try a few different limits and watch how the results array 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.

  2. Fill in the loadPokemon() function. It is already declared async, so you can use await (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/" },
        ...
      ]
    }
    
  3. Pass each Pokémon in the response’s results array to the provided addPokemonCard() 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 the allPokemon array and adds its card (picture, number, name, and checkbox) to the page. It uses split() on the url to pull out the Pokémon’s id, such as 4 in https://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...of loop or forEach(). These two do the same thing:

    for (const item of items) {
        doSomething(item);
    }
    
    items.forEach(item => doSomething(item));
    
    Use whichever one you’re more comfortable with.

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.

  1. Look at the two parameters your function receives:

    • allPokemon is an array of {name, url} objects, one per Pokémon.
    • queryText is 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/" }
    
  2. Implement filterPokemon() to use filter() and return a new array with only the Pokémon whose name contains queryText.

    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 returned true.

    const numbers = [3, 8, 12, 5];
    const bigOnes = numbers.filter(n => n > 4);   // [8, 12, 5]
    

  3. 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(), and trim().

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:

  1. It calls getParty() to get the checked Pokémon as an array of {name, url} objects.
  2. It passes that array to your getPokemonData() function.
  3. It passes the result to your calculateBST() function.
  4. 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.

  1. Look at the data you will be working with. Each url in 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" } },
        ...
      ],
      ...
    }
    
  2. 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 declared async, so you can use await (recommended) or .then(). You can fetch the Pokémon one at a time using a loop, or you can use map() 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 await each 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 with Promise.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);
    

  3. Write calculateBST(pokemonData). It takes the array of full data objects (the output of getPokemonData) 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.