Skip to content

Instantly share code, notes, and snippets.

@annalabrozzi
Last active March 1, 2018 15:14
Show Gist options
  • Save annalabrozzi/cb091fb5d82ab640736f8b5520c1624e to your computer and use it in GitHub Desktop.
Save annalabrozzi/cb091fb5d82ab640736f8b5520c1624e to your computer and use it in GitHub Desktop.
state averages
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<h1>Please look in the code below for 4 JavaScript practice problems.</h1>
<p>(These problems don't include any SVG manipulation, so you will need to open the developer console in order to see the output of your code)</p>
<script>
states = [{name: "Alaska", id: "AK", population: 741894},
{name: "Virginia", id: "VA", population: 8411808},
{name: "Arizona", id: "AZ", population: 6931071},
{name: "Florida", id: "FL", population: 20984400}]
// Problem 1: using d3.mean(), compute and print the average (mean)
// population of the states in the states array
var avg = d3.mean(states, function(d) {
return d.population; });
console.log(avg)
// Problem 2: WITHOUT using d3.mean(), compute and print the average (mean)
// population of the states in the states array
//creating a loop, defining i and giving it an itial value of 0, go through as long as i is less than states.length is less than 0 (there are 4 for length of states), we will add 1 to the value of 1 (i++) as long as this statement is true
//states[0] gives first, states[1] returns second, and so on... and states [i] goes through the loop we created, average += keeps adding averages of each population
console.log("without using d3.mean")
var average = 0;
for (i=0; i < states.length; i++){
average += states[i].population;
}
average = average / states.length;
console.log(average)
console.log('another way of doing it')
var populations = 0;
var numberofstates = 0;
states.forEach(function(d){
populations += d.population;
numberofstates++;
})
var mean = populations/numberofstates;
console.log(mean)//each time we go through the array, it knows we went through it another time
console.log('using a while loop');
//while loop can deliberately make something do something indefinetely and sometimes you want that
var population = 0;
var mean = 0;
var i = 0;
while (i< states.length){
population = population + states[i].population;
i++;
}
mean = population/states.length;
console.log(mean)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment