Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save carlmlane/b688b73dc89e6495f456 to your computer and use it in GitHub Desktop.

Select an option

Save carlmlane/b688b73dc89e6495f456 to your computer and use it in GitHub Desktop.
1. Create a function with a loop that prints out only the odd positioned elements of an array that it takes in.
var myArray = ["Carl", "Addison", "Alex", "Marshall", "Nancy", "Tryana", "Peter"]
// Iterates through array and prints out only oddly-positioned numbers
for (i=0; i<myArray.length; i++) {
if ( i % 2 == 1) {
console.log(myArray[i]);
}
2. Create a function with a loop that prints out only the even numbers of an array that consists of only numbers.
// Creates an array of 40 random numbers between 1-100, sorts them, and prints them out
var myArray = [];
for (i = 0; i < 40; i++) {
myArray.push(Math.round(Math.random() * 100));
}
myArray.sort();
console.log("Array of 40 random numbers between 1-100: "+myArray);
//Creates an array made from evenly numbered items from random array generated above
var evensArray = [];
var findEvens = function(array) {
for (i = 0; i < array.length; i++) {
if (array[i] % 2 === 0) {
evensArray.push(array[i]);
}
evensArray.sort();
}
};
findEvens(myArray);
console.log("Array of even numbers inside above array: "+evensArray);
3. Create a function that takes in two arguments, one is an array and one is a string. The function should loop through the array and return true for each time that the string matches the element the function is looping through.
myArray = ["duck", "duck", "duck", "goose", "duck", "goose", "duck", "duck", "duck", "goose"];
var truthFinder = function (arr, str) {
for (i=0; i<arr.length; i++) {
if (arr[i] === str) {
console.log("True");
}
}
};
truthFinder(myArray, "goose");
4. Use JavaScript's random function inside a while loop to run the loop as long as your variable doesn't equal exactly 50. Limit your random sample to 1-100. Each time the loop runs, print something like this to the console: console.log(runValue + " doesn't equal 50, Run #" + runNumber).
runValue = Math.round(Math.random() * 100);
var runCount = 0;
while ( runValue != 50 ) {
runCount++;
console.log(runValue+" doesn't equal 50m Run # - "+runCount);
runValue = Math.round(Math.random() * 100);
}
Hints:
- You'll have to increment
- Math.random() - http://www.w3schools.com/jsref/jsref_random.asp
- You may have to round with Math.floor()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment