User Tools

Site Tools


en:web_development:tables:arrays

Web Development Lesson 4 - Tables

Javascript Multidimensional Arrays

Objective

We'll continue building our table of stats on the Colombia team, but we'll do it more efficiently with javascript by using arrays and loops.

Setup

  • In your 'project' directory, create a file called 'team.html'.
  • Set up the template using 'html:5' and 'link:css' in the header.
  • Also add a Javascript file using 'script:src' and set src to 'team.js', then create the file 'team.js'.
  • Create the table and add the header row.

team.html

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Surname</th>
      <th>Nationality</th>
      <th class="age">Age</th>
      <th>Position</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
  • Copy the relevant CSS from 'style.css' in your main directory to 'style.css' in your project directory.

style.css

td, th {
  border-width: 1px;
  border-style: solid;
}

td {
  padding: 10px;
}

table {
  border-collapse: collapse;
}

#carlos {
  font-style: italic;
}

.age {
  background-color: yellow;
}

#carlos .age {
  font-weight: 900;
}

td.age {
  font-size: 150%;
}
  • Add the following code to 'team.js' so that our code only runs when the page is ready.

team.js

window.onload = function () {

}

Arrays

  • Just as a list can be represented by an array in Javascript, a table (which is a list of lists) can be represented as an array of arrays. First let's set up a single row.
  • Each row is a list / array containing information about a single player.
window.onload = function () {
    // generate player data
    player = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];
}
  • Now let's display the list.
    // create row text
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";
  • Hopefully this is familiar to you. We did something very similar when creating a list in Javascript.
  • We're creating a long string of code in a text variable called statsRow.
  • The text contains the code for a row including all the appropriate <tr> and <td> tags and the player data.
  • player[] references the data in the list called 'player'.
  • Now that the string is ready we can add it to the table.
    // add row to table
    tableBody = document.getElementsByTagName("tbody")[0];
    newRow    = tableBody.insertRow(0);
    newRow.innerHTML = statsRow;
  • You should also recognise this code.
  • The first (after the comment) line shows the element with tag name <tbody> being assigned to the variable tableBody.
  • Then we insert a new row at position 0 (immediately after the <tbody> tag) of our tableBody element and assign it to a variable called newRow.
  • In the final line of this code, we fill our new row with newRow with the text string we created earlier.
  • Let's look at the complete code so far.
window.onload = function () {
    // generate data
    player = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];

    // create row text
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";

    // add row to table
    tableBody = document.getElementsByTagName("tbody")[0];
    newRow    = tableBody.insertRow(0);
    newRow.innerHTML = statsRow;
}
  • That's a lot of work for just displaying one line, but we don't have to go through the same thing every time.

Functions

  • We want to use the 'create row text' section multiple times (once for each player) so let's move it into its own Javascript function.
  • A function is a block of code that can be called by a button click or from anywhere else in the Javascript code. Remember we did this for our checklists in the previous lesson?
  • Add this function below the existing code.
function createRowText() {
    
}
  • Now move the 'create row text' block inside your new function.
function createRowText() {
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";
}
  • At this point, the function doesn't know what player is and the main code won't have access to statsRow.
  • Add player between () to tell the original code that we need this information.
  • Add a new line at the end with return statsRow; to pass the string back to the main code. It should now look like this.
function createRowText(player) {
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";
    return statsRow;
}

Multidimensional Arrays

  • We really want our program to run through all our players. So we have a list of players each containing a list of stats. In other words, we have an array of arrays or a multidimensional array. Let's start with the data we already know.
  • First, let's update our 'generate data' section to show an array of arrays (list of lists).
    players = [
        ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'],
        ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'],
        ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'],
        ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero']
              ];
  • Note that each line is an element in the larger list, so we separate them by ,.
  • The only ; is at the end of the entire statement.
  • So we are saying that we have an array of arrays (list of lists) called players.
  • We want to show each player in turn, so we need data from players[0], players[1], players[2] and players[3]. Rather than writing out each of these in turn, we can use a javascript loop as follows.
// create text
for (p = 0; p < players.length; p++) {

}
  • Remember this from when you created a list using Javascript? We've replaced i with p . We're running through the code from player 1 (p = 0) until we reach the last player (p < players.length) incrementing each time ( p++ ) so we hit every player.
  • Before we go any further, let's check that we have the correct information.
  • Add a line inside the for loop as follows.
        console.log(p);
  • This will print the value of p in the console, which is a tool that allows you to interact with the javascript code in the page.
  • Open your 'team.html' code in Live Server, which should still just show the table header row.
  • Now open your Developer Tools (click the menu in top right, then select 'More Tools' and 'Developer Tools') and switch to the 'Console' panel.
  • Check that it has printed (in green) the values from 0 to 3. If not, see if you can work out why. Feel free to ask for help.
  • Let's take it a step further and change p to players[p] which should be the data for each player.
  • Check the console again (refresh the page if you need to) and you should see 4 arrays, each with a list of player data. That tells us that we have the correct data ready to use.
  • Now, for each player, we need to create the statsRow as for the single player.
  • We already have a function that does this, so let's call it.
        // create row text
        statsRow = createRowText(players[p]);
  • We've kept the variable name as statsRow because it fits our code for adding to the table, but this is a different variable to the one inside the function. The one inside the function only works inside the function (its 'scope' is the function).
  • createRowText(players[p]) calls the function createRowText and provides it the data belonging to the current player as we saw in the Console.
  • If you check the page again now, you'll only be showing the last player because we're overwriting the player data every time we call the function (statsRow = createRowText(players[p]) reassigns statsRow).
  • Let's move the 'add row to table' block of code inside the 'for loop' so we display each row when the data is ready (and before we lose it).
    for (p = 0; p < players.length; p++) {
        console.log(players[p]);
        // create row text
        statsRow = createRowText(players[p]);

        // add row to table
        tableBody = document.getElementsByTagName("tbody")[0];
        newRow    = tableBody.insertRow(0);
        newRow.innerHTML = statsRow;
    }
  • Run the code now and you'll see that it's still not quite right. All the players are listed, but the order is backwards.
  • This is because we're always adding the new row in the top slot above everything else (.insertRow[0]).
  • We want the row number to increment at the same time as the player data.
        newRow    = tableBody.insertRow(p);
  • There's one last change to make. tableBody doesn't ever change, so there's no need to reassign it every time we go through the loop. Let's move that line above the loop so it's calculated first and never again.
  • Our final code looks like this.
window.onload = function () {
    // generate data
    players = [
        ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'],
        ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'],
        ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'],
        ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero']
              ];

    tableBody = document.getElementsByTagName("tbody")[0];

    // display data
    for (p = 0; p < players.length; p++) {
        // console.log(players[p]);
        // create row text
        statsRow = createRowText(players[p]);

        // add row to table
        newRow    = tableBody.insertRow(p);
        newRow.innerHTML = statsRow;
    }
}

function createRowText(player) {
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";
    return statsRow;
}
  • This looks a lot more efficient now, but you still might think that it's easier to create the table in HTML than Javascript. Ok. What about if we use the full team? Can you imagine building the table with 26 players? What if you're using data with thousands of entries? Creating the array is much easier.

Next: Exercise

en/web_development/tables/arrays.txt · Last modified: 2023/08/16 09:33 (external edit)