This is the curriculum for the 2018 Foxtrot Web Developer Bootcamp.

JavaScript Arrays, Loops & Iteration

Until now, we've only dealt with one piece of information at a time: one number, one string, one element on a page. But often, we need to group things together. For example, what if we wanted to have a list of the months of the year? We'd use an array, which is just a list of things grouped together.

Array is the first example of a collection of data/value as a ordered set of variables.
An array is linear list of elements/variables that can be accessed with an integer index.

For more information see Object Arrays and Eloquent JavaScript

JavaScript Language Array

Declare an array:

var a = [9, 8, 7];
a;

Accessing Elements

a[1];
a[2];
a[0];

Changing Elements

a[1] = 17;
a[1];   // changed
a[0];   // unchanged
a[2];   // unchanged

Adding elements

var b = [];
b;
b[0];
b[0] = 0;
b[1] = 10;

b[5] = 50;
b[5];
b[4];   -> undefined
b;      -> [17, undefined  4, 50]

Array API

Length

a.length    -> 3

Note: length is read-only property, not a function.

Concatenation

Adding element(s) at the end

a[a.length] = 5;
a;              -> [..., 5]
a.concat(6);    -> [..., 6]
a.concat(7,8);  -> [..., 7, 8]
a;              -> [..., 5] // unchanged
var c = a.concat(b);
c;              -> [..., 50]

concat returns a new array but leaves the original array untouched.

Looping

for (var index=0; index<a.length; index++) {
  var element = a[index];
  console.log(element);
}

for (var index=0; index<a.length; index++) {
  console.log(a[index]);
}

Finding An Element

var n = ['Joe', 'Joann', 'Joel'];
n.lastIndexOf('Joann');     -> 1
n.lastIndexOf('Joan');      -> -1 // Not found

Pretty print (convert to String)

n.toString();
n.join();
n.join(", ");
n.join(" and ");

Array Basics Challenge

Array Methods Practice

Below are exercises in using array methods. Beneath each prompt write the code to fulfill the exercise requirement.

Exercise 1

Consider this variable:
var groceryList1 = ["apples", "carrots", "oatmeal"]
Write the code that will add "granola" to the end of array

Exercise 2

Consider this variable:
var groceryList2 = ["chips", "dip", "cookies"]
Write the code that will add "soda" to the end of the original array.

Exercise 3

Consider this variable:
var numbers1 = [1, 2, 3, 4, 5]
Write the code that will add the number 0 to the beginning of the array

Exercise 4

Consider this variable:
var numbers2 = [2, 4, 6, 8, 10]
Write the code that will add the number 0 to the beginning of the original array.

Exercise 5

Consider this variable:
var numbers3 = [2, 13, 6, 8, 4, 2]
Write the code that finds the index of the first appearance of the number 2.

Exercise 6

Write the code that finds the index of the last appearance of the number 2.

Exercise 7

Consider this variable:
var chars = ["y", "a", "r", "r", "a"]
Write the code that brings all the letters in the chars array together into a string.

Exercise 8

Write the code that reverses the order of the letters in the chars array and saves it into a variable called charsReversed.

Loop Practice

The Odd and Even

Write a JavaScript function that will iterate from 0 to 15. For each iteration, it will check if the current number is odd or even, and display a message to the screen.
Sample Output :
"0 is even"
"1 is odd"
"2 is even"

The Fizz Buzz

Write a JavaScript program which iterates the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Javascript Iteration Challenges

For to While

Re-write the following as a while loop:

for (var i=0; i<10; i++) { console.log(i); }

What is the value of i after the loop? Is it the same in both cases?

.. and Back

Re-write the following as a for loop:

var a = 10;
while (a > 0) {
  console.log(a);
  a = a - 1;
}

Is the value of a the same after the loop?

Duplicate Array

Write a Javascript function mergeArray that merges two arrays and removes all duplicate elements.

mergeArray([1, 2, 3], [2, 30, 1]) should return [1, 2, 3, 30]

Order does not matter.

Pre-fill

Write a Javascript function called fillArray to create a specified number of elements with a pre-filled numeric values in an array.

fillArray(6, 0) should return [0, 0, 0, 0, 0, 0]
fillArray(4, 11) should return [11, 11, 11, 11]

Clean Function

Write a Javascript function to filter false, null, 0 and blank values from an array.

filterArrayValues([58, '', 'abcd', true, null, false, 0]) should return [58, "abcd", true]

Sum Target

Write a Javascript function to find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number.

findPair(50, [10,20,10,40,50,60,70] should return [0, 3] or [2, 3] (one or the other or both)
findPair(50, [25,25,10] should return [0, 1] or [1, 0] (but not both)

Order does not matter.

Javascript Hi/Lo Game

Goal

  • Create a function that plays the following game: The computer picks a secret random integer between 1 and 100 (both inclusive), and repeatedly asks the user for guesses.
  • If the user's guess is too high or too low, the computer notifies them of that
  • Otherwise, if the user guesses the secret number correctly, the computer displays a winning message and the game is over.

Hint: See Math.random()

Stretch goal 1

If the user has not guessed the secret number in seven tries, the user loses.

Stretch goal 2

Validate the user's input. If the user puts a anything other than a number, tell the user they can only use numbers.
Hint: To create a number from a string in javascript use parseInt( ). See: Description.

Stretch goal 3

Allow the user to put their name in before the game starts. When the user has won the game, let the user know they have won, using their name.

Magic 8 Ball Challenge

Story

  • As a user I can enter a question on a web page and magically get an answer to my question.

Goal:

  • Create an array with the following answers: Yup!, Fuhgeddaboudit, Maybe, Ask: what would your mother do?, Ask: what would an Australian do, then do the opposite, Your answer here.
  • Input a question from the user.
  • Create a random number to select one of the answers (hint: use Math.random() and change the magnitude).
  • Output the question with the random answer.

Stretch goal:

  • Put the question and answer into a loop that stops when the user enters STOP.
Arrays Challenge

Arrays of Numbers

Create an array with five decimal numbers, and use it for the following:

  • Create a function that finds the highest number.

    • highestNumber([1,4,2]) should return 4
    • highestNumber([-1,-2,-4]) should return -1
    • Hint: create a variable called max, and assign it a reasonable start value; then use forEach: if an element is higher than max, change max.
  • Create a function that finds the lowest number.

    • lowestNumber([1,4,2]) should return 1
    • lowestNumber([-1,-2,-4]) should return -4
  • Create a function that finds the smallest number (the closest to zero).

    • smallestNumber([1,4,2]) should return 1
    • smallestNumber([0.1,0.01,0.001]) should return 0.001
    • smallestNumber([-1,-2,-4]) should return -1
    • smallestNumber([0.1,-0.001]) should return -0.001
  • Create a function that calculate the sum.

    • sum([1,2,3]) should return 6
    • sum([]) should return 0
  • Create a function that calculate the mean value.

    • mean([1,2,3]) should return 2
  • Create a function that finds the index of the highest number.

    • indexHighestNumber([1,4,2]) should return 1
    • indexHighestNumber([-1,-2,-4]) should return 0

Arrays of Strings

Create an array with your siblings names, and an array with your parents names.

  • Sort your siblings names in alphabetical order.

  • Sort your parents names in reverse alphabetical order.

  • Sort all the names in alphabetical order.

    • Hint: Combine the arrays into a single array.
  • Sort all the names in reverse alphabetical order.

  • Create a function that determines if a given name is amongst the names.

Advanced Functions

  • Create a function that returns an array with only the even elements from the array.

    • evenElements([1,2,3,4]) should return [2,4]
    • Hint: use the % operator
    • What happens if there are no even numbers?
  • Create a function that returns an array with only the odd elements from the array.

    • oddElements([1,2,3,4]) should return [1,3]
    • oddElements([2,2,6,4]) should return []

Resources


Arrays Explained

Today's Tentative Schedule


9:15am - Stand Up


9:30am - More Javascript: Decision Structures & Conditional Statements followed by challenges


12:00 noon - Lunch


1pm - Challenge: Hi/Low Game and other challenges


4.30pm - Review


5pm - Class Ends