Read in data and create an array of cities.
- 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
-
Create named function called getCities Get cities receives data
Example:
function getCities(data) { } -
call function from within d3.csv promise function
d3.csv("city-month.csv").then(function(dataInFunction){ var cities = getCities(dataInFunction); -
test output with
console.logfrom inside of function -
assign variable to first line of data
var firstLine = data[0]; -
create empty array below
var firstline, create a new variable calledarrayOfCitiesand assign it to an empty array. -
loop through JavaScript object elements
for (var key in firstLine) { console.log(key); }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.
-
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. -
look at array contents
put the array to console.log after the for loop
-
notice that first element is month and not name of city
-
delete first element using
array.shift()arrayOfCities.shift(); -
return arrayOfCities
-
In the promise function, call
getCitiesand assign the result to the variablecities
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);
}

