Skip to content

Instantly share code, notes, and snippets.

@micha2jm
Last active February 27, 2018 19:07
Show Gist options
  • Save micha2jm/56f485b1302fb5ea15fd575238072e0d to your computer and use it in GitHub Desktop.
Save micha2jm/56f485b1302fb5ea15fd575238072e0d to your computer and use it in GitHub Desktop.
Sample problems: objects and arrays
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 5 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>
// Problem 1: modify array1 so that each object it contains includes the 2 letter state "id"
console.log("Question 1")
array1 = [
{name: "Arizona", location: "Southwest"},
{name: "Virginia", location: "East"},
{name: "Florida", location: "Southeast"}
];
array2 = [
{name: "Virginia", id: "VA"},
{name: "Arizona", id: "AZ"},
{name: "Florida", id: "FL"}
];
array1.forEach(function(a) {
array2.forEach(function(b) {
if (a.name == b.name) {
b.id = a.id;
}
})
})
console.log(array1)
// Problem 2: print all items that are in both array3
// and array4 to the console.
console.log("Question 2")
array3 = ['a','b','c','d'];
array4 = ['a','c','e','f','g'];
array3.forEach(function(a3){
array4.forEach(function(a4){
if (a3 == a4){
console.log(a3)
}
})
})
// Problem 3: 'states' is an array of objects. Sort the array in ascending order by population
console.log("Question 3")
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}]
states.sort(function(a,b){
return d3.ascending(a.population, b.population)
})
console.log(states)
// Problem 4: using console.log() and the appropriate index on the sorted 'states' array, print the state with the smallest population.
console.log("Question 4")
var min = d3.min(states, function(m){return m.population})
states.forEach(function(x){
if (x.population == min){
console.log(x.name)
}
});
// someNumbers is an array containing all integers from 1-10 inclusively
someNumbers = d3.range(1,11)
// Problem 5: using console.log(), a loop,and the modulus operator, print those members of someNumbers that are NOT multiples of 3.
console.log("Question 5")
someNumbers.forEach(function(g){
if (g % 3 == 0 == false){
console.log(g)
}
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment