completed array and loop exercises, started object exercises

pull/295/head
Libby Marchetti 3 years ago
parent d0c066fcb9
commit 541e5bf798

@ -2124,7 +2124,7 @@ const products = [
{ {
_id: 'hedfcg', _id: 'hedfcg',
name: 'TV', name: 'TV',
description: 'Smart TV:Procaster', description: 'Smart TV: Procaster',
price: 400, price: 400,
ratings: [{ userId: 'fg12cy', rate: 5 }], ratings: [{ userId: 'fg12cy', rate: 5 }],
likes: ['fg12cy'], likes: ['fg12cy'],

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!-- <script src="intro.js"></script> -->
<!-- <script src="level-1.js"></script> -->
<!-- <script type="module" src="level_2.js"></script> -->
<!-- <script type="module" src="level_3.js"></script> -->
<script type="module" src="object.js"></script>
</body>
</html>

@ -0,0 +1,141 @@
// file is external source to index.html
// last thing in body
console.log('hello challenge');
// variables declared with let or var can be changed
let firstName = 'LSMarch';
firstName = 'greatest';
var lastName = 'Hacker';
lastName = 'ever';
console.log(`${firstName} ${lastName}`);
// variables declared with const cannot be changed
const PI = 3.14159;
// this won't diplsay and it errors out
//PI = 3.14;
console.log(PI);
const numbers = [0, 3, 6, 9, 12]; // array of numbers
const fruits = ['banana', 'apple', 'peach', 'orange']; // array of strings
// print array and it's length
console.log('Numbers:', numbers);
console.log('Number of numbers:', numbers.length);
console.log('Fruits:', fruits);
console.log('Number of fruits:', fruits.length);
// an array can have values of different types
const array = [
'LSMarch',
3,
false,
{ make: 'Chevy', model: 'Prism' },
{ skills: ['HTML', 'JavaScript', 'CSS', 'React', 'Java', 'Angular'] }
];
console.log(array);
let js = 'JavaScript'
// splits js into an array at each character
const charactersInJavaScript = js.split('');
console.log('Split a string:', charactersInJavaScript);
let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon';
// splits string at comma and returns array
const companies = companiesString.split(',');
console.log('Split a string at ",":', companies);
// can access each element in an array by their index.
// array index starts at 0
let firstFruit = fruits[0];
console.log("Call value at index 0 in fruits array", firstFruit);
let secondFruit = fruits[1];
console.log("Call value at index 0 in fruits array", secondFruit);
// last index can be be accessed as...
let lastIndex = fruits.length - 1;
lastFruit = fruits[lastIndex];
console.log("Call value at last index of fruits array", lastFruit);
// arrays are mutable and we can modify it
numbers[0] = 99;
numbers[1] = 120;
console.log("Modified numbers array:", numbers);
// methods to manipulate an array
const arr = Array();
// just an empty array
console.log("array created using Array constructor", arr);
const eightEmptyValues = Array(8);
console.log("Array of 8 indexes with constructor:", eightEmptyValues);
// creates an array iwth 8 element values with 'X'
const eightXValues = Array(8).fill('X');
console.log("Array of 8 indexes with value of 'X' with constructor:", eightXValues);
// concatenating two arrays
const firstList = [1, 2, 3];
const secondList = [4, 5, 6];
const thirdList = firstList.concat(secondList);
console.log("Concacted firstList and secondList:", thirdList);
// .length returns the length of the array
// indexOf return index of an element
console.log("Shows index of array element:", numbers.indexOf(12));
// if element is not in array returns -1
console.log("Shows index of array element:", numbers.indexOf(22));
// checking to see if something is in an array
let index = fruits.indexOf('apple');
if (index != -1) {
console.log('This fruit is in the array');
} else {
console.log('This fruit is not in the array');
}
// can also use ternary
index != -1 ? console.log('This fruit is in the array') : console.log('This fruit is not in the array')
let indexofAvocado = fruits.indexOf('avocado');
indexofAvocado != -1 ? console.log('This fruit is in the array') : console.log('This fruit is not in the array');
// lastIndexOf gives the index of the last item in the array
const newNums = [1, 2, 3, 4, 5, 3, 1, 2];
console.log('Last index of value in newNums:', newNums.lastIndexOf(2));
console.log('Last index of value in newNums:', newNums.lastIndexOf(6));
console.log('Last index of value in newNums:', newNums.lastIndexOf(1));
// include checks if element is in array and returns boolean
console.log('4 is in the number array:', numbers.includes(4));
console.log('9 is in the numbers array:', numbers.includes(9));
// Array.isArray checks to see if value is indeed an array
console.log('Numbers is an array:', Array.isArray(numbers));
const number = 100;
console.log('Number is an array', Array.isArray(number));
//toString converts array to string (no spaces)
console.log("Numbers array as string", numbers.toString());
// join is used to join elements to array. Argument passed will be joined
// in the array and return as a string;
const webTechs = ['HTML', 'JavaScript', 'CSS', 'React', 'Java', 'Angular'];
console.log("Joins webTechs array with comma and space", webTechs.join(', '));
// slice cuts out multiple items in a range. Takes 2 arguments,
// starting and ending posiion, excludes ending position
console.log("Slice():", numbers.slice());
console.log("Slice(0)", numbers.slice());
console.log("Slice(0, numbers.length)", numbers.slice(0, numbers.length));
console.log("Slice(1, 4", numbers.slice(1, 4));
// splice takes 3 arguments, starting position, number of items to be removed,
// and number of items to be added
const moreNumbers = [1, 2, 3, 4, 5, 6];
moreNumbers.splice()
console.log("Splice() removes all itmes:", moreNumbers.splice());
//moreNumbers.splice(0, 1)
console.log("Splice(0, 1) removes first item:", moreNumbers);
moreNumbers.splice(3, 3, 7, 8, 9)
console.log("removes 3 items and replaces 3 items", moreNumbers);
// push() adds to the end of an existing array
moreNumbers.push(10);
console.log("Push:", moreNumbers);
// pop() removes 1 item from the end of the array
moreNumbers.pop();
console.log("Pop:", moreNumbers);
// shift() removes 1 from the beginning of the array
moreNumbers.shift();
console.log("Shift:", moreNumbers);
// unshift() add to the beginning of the array
moreNumbers.unshift(1);
console.log("Unshift:", moreNumbers);
// reverses the order of the array
moreNumbers.reverse();
console.log("Reverse:", moreNumbers);
// sore() arranges array elements in ascending order.
webTechs.sort();
console.log("Sort:", webTechs);
// Array of arrays
const frontEnd = ["HTML", "CSS", "JavaScript", "Angular", "React", "Redux"];
const backEnd = ["Node", "Express", "SQL", "MongoDB", "Java", "Spring Boot"];
const fullStack = [frontEnd, backEnd];
// returns an array with 2 arrays
console.log("Array in array:", fullStack);

@ -0,0 +1,69 @@
const exercise1_1 = [];
const exercise1_2 = [1, 2, 3, 4, 5, 6];
console.log(exercise1_2.length);
console.log(exercise1_2[0]);
console.log(exercise1_2[3]);
const lastIndex = exercise1_2.length - 1;
console.log(exercise1_2[lastIndex]);
const mixedDataTypes = [
'LSMarch',
5,
{ firstName: 'greatest', lastName: 'ever' },
['HTML', 'CSS', 'JavaScript'],
45,
'React'
];
const itCompanies = [
'Facebook',
'Google',
'Microsoft',
'Apple',
'IBM',
'Oracle',
'Amazon'
];
console.log(itCompanies);
console.log("IT Companies Length:", itCompanies.length);
console.log("First company:", itCompanies[0]);
console.log("Middle Company:", itCompanies[4]);
console.log("Last Company:", itCompanies[itCompanies.length - 1]);
for (let i = 0; i < itCompanies.length; i++) {
console.log(itCompanies[i])
}
for (let i = 0; i < itCompanies.length; i++) {
console.log(itCompanies[i].toUpperCase());
}
console.log(itCompanies.join(', ') + " are big IT companies");
let checkCompany = itCompanies.indexOf('IBM');
checkCompany = -1
? console.log('IBM is in the array')
: console.log('IBM is NOT in the array');
// for (let i = 0; i < itCompanies.length; i++) {
// if (!itCompanies[i].includes('oo')) {
// itCompanies.splice(3, i);
// }
// }
//console.log(itCompanies);
//console.log(itCompanies.sort());
//console.log(itCompanies.reverse());
console.log(itCompanies.slice(0, 3));
console.log(itCompanies.slice(4, 7));
console.log(itCompanies.slice(2, 5));
//console.log(itCompanies.splice(0, 1));
//console.log(itCompanies.splice(6, 1));
//console.log(itCompanies.splice(3, 1));
console.log(itCompanies.splice());

@ -0,0 +1,51 @@
import countries from "./modules/countries.js";
import web_techs from "./modules/web_techs.js";
let text = 'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
let textToSplitPeriod = text.split('.')
let textToString = textToSplitPeriod.toString();
let textTosplitComma = textToString.split(',');
textToString = textTosplitComma.toString();
let words = textToString.split(' ');
console.log('words:', words);
console.log(words.length);
const shoppingCart = [
'Milk', 'Coffee', 'Tea', 'Honey'
];
for (let i = 0; i < shoppingCart.length; i++) {
if (!shoppingCart.includes("Meat")) {
shoppingCart.unshift('Meat');
}
if (!shoppingCart.includes("Sugar")) {
shoppingCart.push("Sugar")
}
if (shoppingCart[i] == "Tea") {
shoppingCart[i] = "Green Tea"
}
}
console.log(shoppingCart);
countries.forEach(country => {
if (country == "Ethiopia") {
console.log(country);
} else {
countries.push("Ethiopia");
}
});
web_techs.forEach(tech => {
if (tech == "Sass") {
console.log("Sass is a CSS preprocess");
} else if (!web_techs.includes("Sass")) {
web_techs.push("Sass");
}
});
console.log(web_techs);
const frontEnd = ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'];
const backEnd = ['Node', 'Express', 'MongoDB'];
const fullStack = frontEnd.concat(backEnd);
console.log(fullStack);

@ -0,0 +1,221 @@
import countries from "./modules/countries.js";
const ages = [
19,
22,
19,
24,
20,
25,
26,
24,
25,
24
];
const sortedAges = ages.sort();
console.log("Min age:", sortedAges[0]);
console.log("Max age:", sortedAges[sortedAges.length - 1]);
console.log("Median age:", sortedAges[4] / 2);
const initialValue = 0;
const reducedAges = ages.reduce((previousValue, currentValue) =>
previousValue + currentValue, initialValue);
console.log("Average age:", reducedAges / 2);
console.log("Age range:", sortedAges[sortedAges.length - 1] - sortedAges[0]);
const compareMin = (min, average) => {
return Math.abs(min - average);
}
const compareMax = (max, average) => {
return Math.abs(max - average);
}
console.log("Compare min:", compareMin(sortedAges[0], (reducedAges / 2)));
console.log("Compare max:", compareMax(sortedAges[sortedAges.length - 1], (reducedAges / 2)));
console.log(countries.slice());
if (countries.length % 2 != 0) {
console.log('Middle countries:', countries[5], 'and', countries[6])
}
const firstHalf = [];
const secondHalf = [];
if ((countries.length - 6) % 2 != 0) {
for (let i = 0; i < countries.length - 6; i++) {
firstHalf.push(countries[i]);
}
for (let i = countries.length - 6; i < countries.length; i++) {
secondHalf.push(countries[i])
}
};
firstHalf.push("Italy")
console.log(firstHalf.length, firstHalf)
console.log(secondHalf.length, secondHalf)
let userAgeInput = prompt("Enter your age: ");
let userAge = parseInt(userAgeInput);
let myAge = 31;
switch (true) {
case userAge > 16:
console.log("You are old enough to drive")
break;
case userAge < 16:
console.log(`"You must wait ${16 - userAge} years to drive`)
default:
break;
}
if (userAge < myAge) {
console.log(`I am ${myAge - userAge} years older than you`)
} else {
console.log(`You are ${userAge - myAge} years older than me`)
}
let a = 4;
let b = 3;
a < b
? console.log(`${a} is less than ${b}`)
: console.log(`${b} is less than ${a}`)
switch (true) {
case userAge % 2 == 0:
console.log(`${userAge} is an even number`);
break;
case userAge % 2 != 0:
console.log(`${userAge} is an odd number`);
break;
default:
break;
}
let scoreInput = prompt('Score: ');
let studentScore = parseInt(scoreInput);
if (80 < studentScore && studentScore < 100) {
console.log(`Student receives an A`)
} else if (70 < studentScore && studentScore < 89) {
console.log(`Student receives a B`);
} else if (60 < studentScore && studentScore < 69) {
console.log(`Student receives a C`);
} else if (50 < studentScore && studentScore < 59) {
console.log(`Studnet receives a D`);
} else if (0 < studentScore && studentScore < 49) {
console.log(`Student receives an F`);
}
let day = prompt('What is the day today?').toLowerCase();
switch (day) {
case 'monday':
console.log(`${day} is a working day`);
break;
case 'tuesday':
console.log(`${day} is a working day`);
break;
case 'wednesday':
console.log(`${day} is a working day`);
break;
case 'thursday':
console.log(`${day} is a working day`);
break;
case 'friday':
console.log(`${day} is a working day`);
break;
case 'saturday':
console.log(`${day} is a weekend`);
break;
case 'sunday':
console.log(`${day} is a weekend`);
break;
default:
console.log(`Enter a valid day`);
break;
}
const month = prompt("Enter a month: ").toLowerCase();
const leapYearInput = prompt("Is it a leap year?").toLocaleLowerCase();
if (leapYearInput == 'yes') {
switch (month) {
case 'january':
console.log(`${month} has 31 days`);
break;
case 'feburary':
console.log(`${month} has 29 days`);
break;
case 'march':
console.log(`${month} has 31 days`);
break;
case 'april':
console.log(`${month} has 30 days`);
break;
case 'may':
console.log(`${month} has 31 days`);
break;
case 'june':
console.log(`${month} has 30 days`);
break;
case 'july':
console.log(`${month} has 31 days`);
break;
case 'august':
console.log(`${month} has 31 days`);
break;
case 'september':
console.log(`${month} has 30 days`);
break;
case 'october':
console.log(`${month} has 31 days`);
break;
case 'november':
console.log(`${month} has 30 days`);
break;
case 'december':
console.log(`${month} has 31 days`);
break;
default:
console.log(`Enter a month`);
break;
}
} else {
switch (month) {
case 'january':
console.log(`${month} has 31 days`);
break;
case 'feburary':
console.log(`${month} has 28 days`);
break;
case 'march':
console.log(`${month} has 31 days`);
break;
case 'april':
console.log(`${month} has 30 days`);
break;
case 'may':
console.log(`${month} has 31 days`);
break;
case 'june':
console.log(`${month} has 30 days`);
break;
case 'july':
console.log(`${month} has 31 days`);
break;
case 'august':
console.log(`${month} has 31 days`);
break;
case 'september':
console.log(`${month} has 30 days`);
break;
case 'october':
console.log(`${month} has 31 days`);
break;
case 'november':
console.log(`${month} has 30 days`);
break;
case 'december':
console.log(`${month} has 31 days`);
break;
default:
console.log(`Enter a month`);
break;
}
}

@ -0,0 +1,15 @@
export const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya',
]
export default countries

@ -0,0 +1,11 @@
export const web_techs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB'
]
export default web_techs

@ -0,0 +1,332 @@
const dog = {};
console.log(dog);
dog.name = 'Spot';
dog.legs = 4;
dog.color = 'spotted';
dog.age = 4;
dog.bark = function () {
return 'woof woof';
};
console.log(dog.name);
console.log(dog.legs);
console.log(dog.color);
console.log(dog.age);
console.log(dog.bark());
dog.breed = 'Dalmation';
dog.getDogInfo = function () {
return `Hi! My name is ${this.name}! I am ${this.age} years old!`
};
console.log(dog.getDogInfo())
const users = {
Alex: {
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: 'asab@asab.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: 'daniel@daniel.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
},
Daniel: {
email: 'daniel@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
age: 20,
isLoggedIn: false,
points: 40
},
John: {
email: 'john@john.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 20,
isLoggedIn: true,
points: 50
},
Thomas: {
email: 'thomas@thomas.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
age: 20,
isLoggedIn: false,
points: 40
},
Paul: {
email: 'paul@paul.com',
skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
age: 20,
isLoggedIn: false,
points: 40
}
}
console.log(users.Alex.skills.length);
console.log(users.Asab.skills.length);
console.log(users.Brook.skills.length);
console.log(users.Daniel.skills.length);
console.log(users.John.skills.length);
console.log(users.Thomas.skills.length);
console.log(users.Paul.skills.length);
let usersLoggedIn = 0;
let pointsOver50 = 0;
if (users.Alex.isLoggedIn) {
usersLoggedIn++;
}
if (users.Asab.isLoggedIn) {
usersLoggedIn++;
}
if (users.Brook.isLoggedIn) {
usersLoggedIn++;
}
if (users.Daniel.isLoggedIn) {
usersLoggedIn++;
}
if (users.John.isLoggedIn) {
usersLoggedIn++;
}
if (users.Thomas.isLoggedIn) {
usersLoggedIn++;
}
if (users.Alex.points >= 50) {
pointsOver50++;
}
if (users.Asab.points >= 50) {
pointsOver50++;
}
if (users.Brook.points >= 50) {
pointsOver50++;
}
if (users.Daniel.points >= 50) {
pointsOver50++;
}
if (users.John.points >= 50) {
pointsOver50++;
}
if (users.Thomas.points >= 50) {
pointsOver50++;
}
console.log(usersLoggedIn)
console.log(pointsOver50)
// MongoDB, Express, React, Node
let mernDevs = 0;
if (users.Asab.skills.includes('MongoDB')
&& users.Asab.skills.includes('Express')
&& users.Asab.skills.includes('React')
&& users.Asab.skills.includes('Node'))
mernDevs++;
if (users.Alex.skills.includes('MongoDB')
&& users.Alex.skills.includes('Express')
&& users.Alex.skills.includes('React')
&& users.Alex.skills.includes('Node'))
mernDevs++;
console.log(mernDevs);
users.Libby = {
email: 'lsmarchetti01@gmail.com',
skills: ['HTML', 'CSS', 'JavaScript', 'TypeScript', 'Angular', 'React',
'SQL', 'MongoDB', 'Express', 'Java', 'Springboot', 'Node'],
age: 31,
isLoggedIn: true,
points: 60
}
console.log(users.Libby);
const entries = Object.entries(users)
console.log(entries)
const countries2 = {
USA: {
capital: 'Washington DC',
population: 1000,
language: ['English', 'Spanish', 'Node']
}
}
console.log(countries2.USA);
const personAccount = {
firstName: 'Bob',
lastName: 'Bobert',
incomes: [53, 100, 98, 34],
expenses: [5, 66, 100],
totalIncome: function (incomes) {
const initial = 0;
let total = incomes.reduce((previous, current) =>
previous + current, initial
)
return total;
},
totalExpense: function (expenses) {
const initial = 0;
let total = expenses.reduce((previous, current) =>
previous + current, initial
)
return total;
},
addIncome: function (income) {
this.incomes.push(income);
},
addExpense: function (expense) {
this.expenses.push(expense)
},
accountBalance: function () {
let balance = this.totalIncome(this.incomes) - this.totalExpense(this.expenses)
return balance;
},
accountInfo: function () {
console.log(`${this.firstName} ${this.lastName}, your account balance is
${this.accountBalance()}`)
}
}
console.log(personAccount.totalIncome(personAccount.incomes))
console.log(personAccount.totalExpense(personAccount.expenses))
personAccount.accountInfo();
const usersArr = [
{
_id: 'ab12ex',
username: 'Alex',
email: 'alex@alex.com',
password: '123123',
createdAt: '08/01/2020 9:00 AM',
isLoggedIn: false,
},
{
_id: 'fg12cy',
username: 'Asab',
email: 'asab@asab.com',
password: '123456',
createdAt: '08/01/2020 9:30 AM',
isLoggedIn: true,
},
{
_id: 'zwf8md',
username: 'Brook',
email: 'brook@brook.com',
password: '123111',
createdAt: '08/01/2020 9:45 AM',
isLoggedIn: true,
},
{
_id: 'eefamr',
username: 'Martha',
email: 'martha@martha.com',
password: '123222',
createdAt: '08/01/2020 9:50 AM',
isLoggedIn: false,
},
{
_id: 'ghderc',
username: 'Thomas',
email: 'thomas@thomas.com',
password: '123333',
createdAt: '08/01/2020 10:00 AM',
isLoggedIn: false,
},
];
const userToAdd = {
_id: 'afwogf',
username: 'bob',
email: 'bob@bob.com',
passowrd: '5544234'
};
const userNotToAdd = {
_id: 'ghderc',
username: 'Thomas',
email: 'thomas@thomas.com',
password: '123333',
createdAt: '08/01/2020 10:00 AM',
isLoggedIn: false,
};
const signUp = (newUser) => {
let userExists = false;
usersArr.forEach(existingUser => {
if (newUser._id == existingUser._id) {
console.log('User already exists');
userExists = true;
}
})
if (!userExists) {
console.log('User added');
usersArr.push(newUser);
}
}
signUp(userToAdd)
console.log(usersArr)
const signIn = (user) => {
user.isLoggedIn = true;
console.log(user.isLoggedIn)
}
const products = [
{
_id: 'eedfcf',
name: 'mobile phone',
description: 'Huawei Honor',
price: 200,
ratings: [
{ userId: 'fg12cy', rate: 5 },
{ userId: 'zwf8md', rate: 4.5 },
],
likes: [],
},
{
_id: 'aegfal',
name: 'Laptop',
description: 'MacPro: System Darwin',
price: 2500,
ratings: [],
likes: ['fg12cy'],
},
{
_id: 'hedfcg',
name: 'TV',
description: 'Smart TV: Procaster',
price: 400,
ratings: [{ userId: 'fg12cy', rate: 5 }],
likes: ['fg12cy'],
},
]
const rateProduct = (user, product) => {
for (let i = 0; i < products.length; i++) {
if (product._id == products[i]._id) {
product.ratings.push({ userId: user._id, rate: 1 });
console.log(products[i].ratings);
}
}
}
rateProduct(userNotToAdd, products[1]);
const averageRating = (product) => {
const initial = 0;
console.log(average)
}
averageRating(products[0])
Loading…
Cancel
Save