Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active September 16, 2018 21:23
Show Gist options
  • Select an option

  • Save codetricity/ccf9dc0c3d400608f95d318856d49741 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/ccf9dc0c3d400608f95d318856d49741 to your computer and use it in GitHub Desktop.
temp by month pt 3. Use of JavaScript arrays

temp by month pt 3. Use of JavaScript arrays

Section Goal

Read in data and create an array of cities.

array of cities

Learning Objectives

  • review JavaScript named functions
  • review JavaScript arrays
  • use of for ... in syntax for JavaScript object
  • Use of arrayName.push( information ) for JavaScript arrays
  • use of arrayName.shift() to delete first element of array

Steps

  1. Create named function called getCities Get cities receives data

    Example:

    function getCities(data) {
    }
    
  2. call function from within d3.csv promise function

     d3.csv("city-month.csv").then(function(dataInFunction){
       var cities = getCities(dataInFunction);
    
  3. test output with console.log from inside of function

  4. assign variable to first line of data

     var firstLine = data[0];
    
  5. create empty array below var firstline, create a new variable called arrayOfCities and assign it to an empty array.

  6. loop through JavaScript object elements

     for (var key in firstLine) {
         console.log(key);
     }
    

    cities

    You now have a list of cities. You need to add them to an array so that you can use the cities in the rest of your program.

  7. add element to end of array with arrayName.push

    The array is currently empty. []

    Use arrayOfCities.push(key) to add the key to the end of the array.

  8. look at array contents

    put the array to console.log after the for loop

  9. notice that first element is month and not name of city

  10. delete first element using array.shift()

     arrayOfCities.shift();
    
  11. return arrayOfCities

  12. In the promise function, call getCities and assign the result to the variable cities


Full program

  d3.csv("city-month.csv").then(function(dataInFunction){
      var cities = getCities(dataInFunction);
      // console.log(cities);
  });

  function getCities(data) {
      // only use the first object
      var firstLine = data[0];

      // create an empty array to hold the names of cities
      var arrayOfCities = [];

      // loop through object
      for (var key in firstLine) {
          console.log(key);
          arrayOfCities.push(key);
      }

      // delete first element as the first
      // element is the month

      arrayOfCities.shift();

      return (arrayOfCities);
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment