Built with blockbuilder.org
forked from scresawn's block: Sample problems: objects and arrays
forked from scresawn's block: Sample problems 2: objects and arrays
forked from scresawn's block: Sample problems 3: objects and arrays
license: mit |
Built with blockbuilder.org
forked from scresawn's block: Sample problems: objects and arrays
forked from scresawn's block: Sample problems 2: objects and arrays
forked from scresawn's block: Sample problems 3: objects and arrays
<!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 | |
console.log('Question : 1 "d3.mean" Solution') | |
var population_mean = d3.mean(states, function(i){ | |
return i.population; | |
}) | |
console.log(population_mean) | |
// Problem 2: WITHOUT using d3.mean(), compute and print the average (mean) | |
// population of the states in the states array | |
console.log('Question : 2 "for" Solution') | |
var average = 0; | |
for(i = 0; i < states.length; i++){ | |
average += states[i].population; | |
} | |
average = average / states.length; | |
console.log(average) | |
//How to do Question 2 with a forEach loop: | |
console.log('Question : 2 "forEach" Solution') | |
var populations = 0; | |
states.forEach(function (d){ | |
populations += d.population; | |
}) | |
var mean = populations / states.length; | |
console.log(mean) | |
// How to do Question 2 with a while loop | |
console.log('Question : 2 "while" Solution') | |
var population = 0; | |
var mean2 = 0; | |
var i = 0; | |
while(i < states.length) { | |
population += states[i].population; | |
i++; | |
} | |
mean2 = population / states.length | |
console.log(mean2) | |
</script> | |
</body> |