udacity lesson 6 arrays

In this example below you will see how to do a udacity lesson 6 arrays with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 120hit, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 120hit ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>udacity lesson 6 arrays</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/120hit/udacity-lesson-6-arrays-VMawBR */
==============creating a array================
  
Arrays
An array is useful because it stores multiple values into a single, organized data structure. You can define a new array by listing values separated with commas between square brackets [].

// creates a `donuts` array with three strings
var donuts = ["glazed", "powdered", "jelly"];
But strings aren’t the only type of data you can store in an array. You can also store numbers, booleans… and really anything!

// creates a `mixedData` array with mixed data types
var mixedData = ["abcd", 1, true, undefined, null, "all the things"];
You can even store an array in an array to create a nested array!

// creates a `arraysInArrays` array with three arrays
var arraysInArrays = [[1, 2, 3], ["Julia", "James"], [true, false, true, false]];
Nested arrays can be particularly hard to read, so it's common to write them on one line, using a newline after each comma:

var arraysInArrays = [
  [1, 2, 3], 
  ["Julia", "James"], 
  [true, false, true, false]
];
--------------example----------------------------------
var houseMembers = ["daisy", "mamu", "rohit"];

document.write(houseMembers[0]);
--------------------changing the element of an array---------------------------------------------------
var donuts = ["glazed", "powdered", "sprinkled"];

donuts[1] = "glazed cruller";

console.log(donuts[1]);

====array index==========
Indexing
Remember that elements in an array are indexed starting at the position 0. To access an element in an array, use the name of the array immediately followed by square brackets containing the index of the value you want to access.

var donuts = ["glazed", "powdered", "sprinkled"];
console.log(donuts[0]); // "glazed" is the first element in the `donuts` array
Prints: "glazed"
One thing to be aware of is if you try to access an element at an index that does not exist, a value of undefined will be returned back.

console.log(donuts[3]); // the fourth element in `donuts` array does not exist!
Prints: undefined


-------quiz building the crew---------

The space western TV drama Firefly premiered in the United States on September 20, 2002. Although the show only featured fourteen episodes and was canceled during its first season, it continues to remain popular today with a growing fan base. In the show, the captain Mal, played by Nathan Fillion, leads a crew of renegades on the spaceship Serenity.

Directions:
Create an array called crew to organize the Serenity’s crew and set it equal to the variables below . You don't need to type out the actual strings, just use the provided variables.

var captain = "Mal";
var second = "Zoe";
var pilot = "Wash";
var companion = "Inara";
var mercenary = "Jayne";
var mechanic = "Kaylee";
Then, print the crew array to the console.

---code----
var crew = [captain, second, piolot, companion, mercenary, machanic];
console.log(crew)

------quiz the price is right 6-3----
Quiz-3
Starting with this array of prices, change the prices of the
1st, 3rd, and 7th elements in the array.

var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];
TIP: The 1st element of any array has an index of 0.
Afterwards, print out the prices array to the console.

Code:
var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];

prices[0]=2.45;
prices[2]=88.67;
prices[6]=55.55;
console.log(prices);

Output:
[ 2.45, 48.11, 88.67, 8.5, 9.99, 1, 55.55, 67 ]

------------------array properties and methods----------------------------------


reverse method 
reverses the order of the elements in an array

sort 
sorts the element in an array

push and pop
two methods that allow us to add and remove elements from array

------------how to find out how many array elelments are in the variables for loops --

var myArray = [3, false, "bye", true , "hello", 6];
consle.log(myArray.lenght);

out put = "6"

[methods] = [special] [pre defined] functions] that a [data structure] can call

arrays are special kind of objects 

TIP: JavaScript provides a large number of built-in methods for modifying arrays and accessing values in an array, check out the MDN Documentation, or type []. into the JavaScript console for a list of all the available Array methods.

================================Length=======================
 
array inside an array count as one, unique elememt in the array 
array.length: you can find the length of an array by using its length property


ex-array inside an array
QUIZ QUESTION

What is the length of the following inventory array?

var inventory = [
  ["gold pieces", 25],
  ["belt", 4],
  ["ring", 1],
  ["shoes", 2]
];

--OP--4------------------------------

ex--finding the length of an array

var donuts = ["glazed", "powdered", "sprinkled"];
console.log(donuts.length);


============================push():adding==================
push is a way to modify an array, and it is an built in methods for adding elements from an array . the two most common methods for modifying an array are push and pop.

var x = ["y1", "y2", "y3"]
x.push("y4"); 

returns: 3
-----------------------------------------------------------------------------
pushes(adds) element(string or other data types)= "y4" to the end of an var x array, push also returns the lenght of the array after an element has been added.
the push method will pass a value but not for the pop method


=================pop():remove=================================

x.push("y"); was the add feature but pop is removing an element at the end of the array, 
  if you keep inputing "x.pop();" say like 2 or 3 times, the pop feature will keep removing the last element
  from an array and untill there is no elements left in the var array. the pop method does not need to pass an value bcuz it is removing an element.
  
  ex
  var donuts = ["x", "y", "Z"];

  donuts.pop();
  donuts.pop();
  donuts.pop();

===================splice():removing element anywhere from the array====================
Splice
splice() is another handy method that allows you to add and remove elements from anywhere within an array.

While push() and pop() limit you to adding and removing elements from the end of an array, splice() lets you specify the index location to add new elements, as well as the number of elements you'd like to delete (if any).

ex-----------------------------------------------

var donuts = ["x" , "y", "z"];

donuts.splice(1,1,"R","S");

The first argument(1) represents the starting index from where you want to change the array, the second argument(1)represents the numbers of elements you want to remove, and the remaining arguments represent the elements you want to add.
------------------------------------
returns: "y"
donut array: ["x", "R", "S"]

--if ex----------------------------------
var donuts = ["x" , "y", "z"];
donuts.splice(1,0,"R","S")

then the following array would look like this
------------------------------------------------
 return ["X", "Y", "R", "S", "Z"]

--
because it is saying at index 1 add r and s and 0 means dont remove any array elements

--another eg----
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); // insert 'drum' at 2-index position
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); // remove 1 item at 2-index position (that is, "drum")
// myFish is ["angel", "clown","mandarin", "sturgeon"]


==========================================colors of the rainbow 6-4=================
Directions:
James was creating an array with the colors of the rainbow, and he forgot some colors. The standard rainbow colors are usually listed in this order:

var rainbow = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
but James had this:

var rainbow = ["Red", "Orange", "Blackberry", "Blue"];
Using only the splice() method, insert the missing colors into the array, and remove the color "Blackberry" by following these steps:

Remove "Blackberry"
Add "Yellow" and "Green"
Add "Purple"

---code---
var rainbow = [
  'Red', 'Orange',
  'Blackberry',
  'Blue'
]

rainbow.splice(2,1,'Yellow', 'Green');
rainbow.push('Blue');
console.log(rainbow);

===================Quidditch===================================
In the Harry Potter novels, children attending the Hogwarts School of Witchcraft and Wizardry belong to one of four houses: Gryffindor, Hufflepuff, Ravenclaw, or Slytherin. Each year, the houses assemble a Quidditch team of seven players to compete for the coveted Quidditch Cup.

Consider the following array.  

var team = ["Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry Potter"];

Directions:
Create a function called hasEnoughPlayers() that takes the team array as an argument and returns true or false depending on if the array has at least seven players.

------code1----
function hasEnoughPlayers(team){
  if(team.length >= 7;){
    return true;
  }else {
    return false;
  }
}

var team = ["Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry Potter"];
console.log(hasEnoughPlayers(team))

----code2----
function hasEnoughPlayers(team){
  return team.length >= 7;
}

var team = ["Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry Potter"];
console.log(hasEnoughPlayers(team))

=========joining the crew= 6-6==================
Directions:
In an earlier exercise, you created a crew array to represent Mal’s crew from the hit show Firefly.

var captain = "Mal";
var second = "Zoe";
var pilot = "Wash";
var companion = "Inara";
var mercenary = "Jayne";
var mechanic = "Kaylee";

var crew = [captain, second, pilot, companion, mercenary, mechanic];
Later in the show, Mal takes on three new crew members named "Simon", "River", and "Book". Use the push() method to add the three new crew members to the crew array.

var doctor = "Simon";
var sister = "River";
var shepherd = "Book";

---------------code-----
/*
 * Programming Quiz: Joining the Crew (6-6)
 */

var captain = "Mal";
var second = "Zoe";
var pilot = "Wash";
var companion = "Inara";
var mercenary = "Jayne";
var mechanic = "Kaylee";

var crew = [captain, second, pilot, companion, mercenary, mechanic];

var doctor = "Simon";
var sister = "River";
var shepherd = "Book";


----my addon code---------------------------------
crew.push(doctor, sister, shepherd);
console.log(crew);

=======checking out the docs 6-7=============
QUESTION 1 OF 4

Use the MDN Documentation to determine which of these methods would be best for reversing elements in this array:

var reverseMe = ["h", "e", "l", "l", "o"];

---code--
reverse()

--explanation---
You got it! Here's the code you could write to reverse the array above:

reverseMe.reverse();
Returns: [ 'o', 'l', 'l', 'e', 'h' ]

-----------------------------------------------
QUESTION 2 OF 4

What would be the best array method to sort the elements in this array:

var sortMe = [2, 1, 10, 7, 6];

--code---
sort()

--explanation---
Yep, the sort() method can sort an array.

sortMe.sort();
Returns: [1, 10, 2, 6, 7]
Did you notice that 10 appears before 2? Traditionally, the number 2 comes before 10. But in the .sort() method, numbers are converted to Unicode strings, so 10 comes before 2 in [Unicode order].

---------------------------------------------------
QUESTION 3 OF 4

What method(s) could you use to remove the first element from this array:

var removeFirstElement = ["a", "b", "c"];

----code--
shift() //The shift() method removes the first element from an array and returns that element. This method changes the length of the array.
splice() //The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
slice() /*The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.*/

--explanation---
shift() will remove the first element from an array.

splice() can be used if you specify the index of the first element, and indicate that you want to delete 1 element.

slice() allows you to create a copy of the array between two indices. You just exclude the index of the first element!
CONTINUE

-----------------------------------------------------
QUESTION 4 OF 4

What method would be best for changing this array into a string?

var turnMeIntoAString = ["U", "d", "a", "c", "i", "t", "y"];

--code---
  join()

--e--
That's right! You can combine the elements in an array to form a string using the join() method.

turnMeIntoAString.join('');
Returns: Udacity


=========================array loop===
Array Loops
Once the data is in the array, you want to be able to efficiently access and manipulate each element in the array without writing repetitive code for each element.

For instance, if this was our original donuts array:

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];
and we decided to make all the same donut types, but only sell them as donut holes instead, we could write the following code:

donuts[0] += " hole";
donuts[1] += " hole";
donuts[2] += " hole";
donuts array: ["jelly donut hole", "chocolate donut hole", "glazed donut hole"]
But remember, you have another powerful tool at your disposal, loops!

To loop through an array, you can use a variable to represent the index in the array, and then loop over that index to perform whatever manipulations your heart desires.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];

// the variable `i` is used to step through each element in the array
for (var i = 0; i < donuts.length; i++) {
    donuts[i] += " hole";
    donuts[i] = donuts[i].toUpperCase();
}
donuts array: ["JELLY DONUT HOLE", "CHOCOLATE DONUT HOLE", "GLAZED DONUT HOLE"]
In this example, the variable i is being used to represent the index of the array. As i is incremented, you are stepping over each element in the array starting from 0 until donuts.length - 1 (donuts.length is out of bounds).

//in the array loop we use for loop and the i index method, also inside the for loop we use array[i] += " string" ;
//and also if we want to add a feature like upper case then we use array = array[i].desired method 

var soccerPlayers = ["Ronadinho", "Ronaldo", "Rohit", "Rojan", "Rojesh", "Pro"];

soccerPlayers[0] += " was my first insparation";
soccerPlayers[1] += " pushed me to become great";
soccerPlayers[2] += " will never stop believing in himself!";
soccerPlayers[3] += " shows he has determination to keep pushing";
soccerPlayers[4] += " the always humble person";
soccerPlayers[5] += " the person, who says hard work pays off";

for (i = 0; i < soccerPlayers.length; i++){
  soccerPlayers[i] += " , just do it";
}
 
console.log(soccerPlayers[0]);

===============.forEach() loop=================================================
The forEach() method gives you an alternative way to iterate over an array, and manipulate each element in the array with an inline function expression.
Notice that the forEach() method iterates over the array without the need of an explicitly defined index. In the example below, Strain corresponds to the element in the array itself. This is different from a for or while loop where an index is used to access each element in the array:

the var weedStrain is using a inline function style

//first we have the classic var called weeedStrain with 3 different arrays
//then we input a new method called .forEach()
//we add the var weedStrain with the .forEach() method
//along with the forEach() method there is a function with a parameter called Strain
//inside the function there is the same function parameter with the add and equal and the desired "string";
//and finally we end it with a console.log(Strain);
var weedStrain = ["Blue Dream ", "White Widow", "Kush OG"];

weedStrain.forEach(function(Strain){
  Strain += " strain";
  Strain = Strain.toUpperCase();
  console.log(Strain);
});

---prints--
Blue Dream strain
White Widow strain
Kush OG strain

---function with multiple parameters without using the inline function style-----------------
function A (element , index , array){
  console.log("element:" + element);
  console.log("index:" + index);
  console.log("array:" + array);
}

myArray.forEach(A);

====================quiz another type of loop=========
Directions:
Use the array's forEach() method to loop over the following array and add 100 to each of the values if the value is divisible by 3.

var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139];

/*
 * Programming Quiz: Another Type of Loop (6-8)
 *
 * Use the existing `test` variable and write a `forEach` loop
 * that adds 100 to each number that is divisible by 3.
 *
 * Things to note:
 *  - you must use an `if` statement to verify code is divisible by 3
 *  - you can use `console.log` to verify the `test` variable when you're finished looping
 */

var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
    19, 300, 3775, 299, 36, 209, 148, 169, 299,
    6, 109, 20, 58, 139, 59, 3, 1, 139
];

// Write your code here
test.forEach(function(num, index, array){
if(num % 3 === 0)
{array[index] = num += 100;} });
console.log(test);

test.forEach(function(num, index, array){
if(num % 3 === 0)
{array[index] = num += 100;} });
console.log(test);

---------for loop with arrays-----
//for loops is convient on where to start(var i = 0)/stop(break statement)/add function(i = i + 2)
var array = [1, 2 ,3 ,4 5];

for(var i =  0; i <= array.length; i = i + 2 ){
  console.log(array[i]);
  if(i === 2){
    break;
  }
}     //1 3 5 

-------forEach() with arrays----------
//forEach is when you are looping every element from start to finish \
//also forEach function lets us target and pinpoint the index you want vs looping with for loop

var x = [1,2,4,5,6];

x.forEach(function(elem){
  console.log(elem);
});

===============.map(func)========
//.map(func) lets us rewrite from a original array and create a new array
//so this lets us easily manipulate data by creating a new array
  
var array = [1,2,3,4,5];
var newArray = array.map(function(elem){
  elem = elem + 100;
  return elem;
});  //newArray : [101, 102, 103, 104, 105]

Using forEach() will not be useful if you want to permanently modify the original array. forEach() always returns undefined. However, creating a new array from an existing array is simple with the powerful map() method.

With the map() method, you can take an array, perform some operation on each element of the array, and return a new array.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"]
var improvedDonuts = donuts.map(function(donut) {
  donut += " hole";
  donut = donut.toUpperCase();
  return donut;
});
donuts array: ["jelly donut", "chocolate donut", "glazed donut"]
improvedDonuts array: ["JELLY DONUT HOLE", "CHOCOLATE DONUT HOLE", "GLAZED DONUT HOLE"]
Oh man, did you just see that? The map() method accepts one argument, a function that will be used to manipulate each element in the array. In the above example, we used a function expression to pass that function into map(). This function is taking in one argument, donut which corresponds to each element in the donuts array. You no longer need to iterate over the indices anymore. map() does all that work for you.


==============i got bills quiz=========
  Directions:
Use the map() method to take the array of bill amounts shown below, and create a second array of numbers called totals that shows the bill amounts with a 15% tip added.

var bills = [50.23, 19.12, 34.01, 100.11, 12.15, 9.90, 29.11, 12.99, 10.00, 99.22, 102.20, 100.10, 6.77, 2.22];
Print out the new totals array using console.log.

TIP: Check out the toFixed() method for numbers to help with rounding the values to a maximum of 2 decimal places. Note, that the method returns a string to maintain the "fixed" format of the number. So, if you want to convert the string back to a number, you can cast it or convert it back to a number:
Number("1");
Returns: 1
Your Code:
/*
 * Programming Quiz: I Got Bills (6-9)
 */

var bills = [50.23, 19.12, 34.01, 100.11, 12.15, 9.90,
29.11, 12.99, 10.00, 99.22, 102.20, 100.10, 6.77, 2.22];

//my code

var totals = bills.map(function(tip){
  tip += tip * 0.15;
  return Number(tip.toFixed(2));
});
console.log(totals);

===========array inside an arrray====
think of an array inside an array as a cell or grid line
in order to pinpoint the specific array element we are going to use 
for loop nested inside another for loop
the parent for loop will find the row and the baby for loop will find the column in this example below
the output will be each string with an /n 
  
------------------example---------------------------------------------  
  
var  donutBox = [ 
["glazed", "normal"],
["jelly", "leche"]
];

for(row = 0; row < donutBox.length; row++){
  for(colum = 0; colum < donutBox[row].length; colum++){
    console.log(donutBox[row][colum]);
  }
}

===quiz===nested numbers 6-10=======================
Directions:
Use a nested for loop to take the numbers array below and replace all of the values that are divisible by 2 (even numbers) with the string "even" and all other numbers with the string "odd".

var numbers = [
    [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
    [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
    [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
    [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
    [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
    [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
    [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
    [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
    [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
    [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];

--code---
for(var i = 0, n = numbers.length; i < n; i++){
  for(var j = 0, m = numbers[i].length; j < m; j++){
    numbers[i][j] = numbers[i][j] % 2 === 0 ? "even" : "odd";
  }
}

---
for (var i = 0, n = numbers.length; i < n; i++) {
    for (var j = 0, m = numbers[i].length; j < m; j++) {
        numbers[i][j] = numbers[i][j] % 2 === 0 ? "even" : "odd";
    }
}

Comments