Forked from PrimeTimeTran/people extra credit assignment.js
Last active
June 11, 2020 03:01
-
-
Save nnguyen150468/650eb78e378841f0c2bd78028ed1f737 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Objectives | |
// Our goal with these exercises is to use arrays, objects, and the fundamental building blocks of JS to query our data | |
// and make new assertions. From a list of people whose attributes we have, what conclusions can be drawn? | |
// Hint | |
// 1. The most important piece of data we will work with is the people array below. | |
// 2. Take a moment to think about the objects in the array. | |
// 3. Contemplate how we could sort people based on the data we have about them. | |
// 4. All functions we write in this exercise will take the people array as it's only argument | |
const people = [{ | |
firstName: 'Loi', | |
lastName: 'Tran', | |
age: 18, | |
occupation: 'Instructor', | |
company: 'CoderSchool', | |
favoriteSinger: 'Taylor Swift', | |
favoriteQuote: 'If it was easy everyone would do it', | |
favoriteColor: 'red', | |
nationality: 'USA', | |
friendsCount: 100, | |
followers: 200, | |
height: '160mm', | |
weight: '70kg' | |
}, | |
{ | |
firstName: 'Charles', | |
lastName: 'Lee', | |
age: 19, | |
occupation: 'Instructor', | |
company: 'CoderSchool', | |
favoriteSinger: 'Justin Bieber', | |
favoriteQuote: 'What one programmer can in a month, two programs can do in two', | |
favoriteColor: 'red', | |
nationality: 'USA', | |
friendsCount: 200, | |
followers: 300, | |
height: '180mm', | |
weight: '50kg' | |
}, | |
{ | |
firstName: 'Hoa', | |
lastName: 'Huynh', | |
age: 23, | |
occupation: 'Student', | |
company: 'CoderSchool', | |
favoriteSinger: 'John Mayer', | |
favoriteQuote: 'Make the world want to fork you on github', | |
favoriteColor: 'black', | |
nationality: 'VN', | |
friendsCount: 500, | |
followers: 600, | |
height: '175mm', | |
weight: '54kg' | |
}, | |
{ | |
firstName: 'Anh', | |
lastName: 'Nguyen', | |
age: 18, | |
occupation: 'Student', | |
company: 'CoderSchool', | |
favoriteSinger: 'None', | |
favoriteQuote: "You dont have to be great to start, but you have to start to be great. - Zig Ziglar", | |
favoriteColor: 'black', | |
nationality: 'Vietnamese', | |
friendsCount: 900, | |
followers: 100, | |
height: '171mm', | |
weight: '58kg' | |
}, | |
{ | |
firstName: 'Philip', | |
lastName: 'Nguyen', | |
age: 26, | |
occupation: 'novice programmer', | |
company: 'CoderSchool', | |
favoriteSinger: 'Action Bronson', | |
favoriteQuote: 'Im here to learn coding and chew bubblegum, and Im fresh outta bubblegum.', | |
favoriteColor: 'red', | |
nationality: 'Murrican', | |
friendsCount: 200, | |
followers: 900, | |
height: '173mm', | |
weight: '59kg' | |
}, | |
{ | |
firstName: 'Huy', | |
lastName: 'Nguyen', | |
age: 26, | |
occupation: 'Student', | |
company: 'CoderSchool', | |
favoriteSinger: 'Maroon5', | |
favoriteQuote: "You only live once, but if you do it right, once is enough", | |
favoriteColor: 'Blue', | |
nationality: 'VN', | |
friendsCount: 500, | |
followers: 700, | |
height: '174mm', | |
weight: '61kg' | |
}, | |
{ | |
firstName: 'Hieu', | |
lastName: 'Nguyen', | |
age: 25, | |
occupation: 'Code learner', | |
company: 'CoderSchool', | |
favoriteSinger: 'Leona Lewis', | |
favoriteQuote: "I meant, said Ipslore bitterly, what is there in this world that truly makes living worthwhile? Death thought about it. ᴄᴀᴛs, he said eventually. ᴄᴀᴛs ᴀʀᴇ ɴɪᴄᴇ.", | |
favoriteColor: 'blue', | |
nationality: 'VN', | |
friendsCount: 400, | |
followers: 300, | |
height: '150mm', | |
weight: '54kg' | |
}, | |
{ | |
firstName: 'Henry', | |
lastName: 'Nguyen', | |
age: 15, | |
occupation: 'student', | |
company: 'CoderSchool', | |
favoriteSinger: 'VyVy', | |
favoriteQuote: 'Mind over mater', | |
favoriteColor: 'white', | |
nationality: 'VN', | |
friendsCount: 600, | |
followers: 300, | |
height: '159mm', | |
weight: '58kg' | |
}] | |
// 1. Define a function getCoderSchoolStaff() which takes the people array as an argument | |
// and returns an array of people who work at 'CoderSchool'. | |
// We would want it to look something like this [{ firstName: 'Loi', ...}, { firstName: 'Charles', ...}] | |
const getCoderSchoolStaff = (arr) => { | |
return arr.filter(el => el.company==="CoderSchool" && el.occupation === "Instructor") | |
} | |
getCoderSchoolStaff(people) | |
const getCoderSchoolStaff2 = (arr) => { | |
const coderSchoolStaff = [] | |
arr.map(el => { | |
if(el.company === "CoderSchool" && el.occupation==="Instructor"){ | |
coderSchoolStaff.push(el) | |
} | |
}) | |
return coderSchoolStaff | |
} | |
getCoderSchoolStaff2(people) | |
// ------------------------------------------------------- README ------------------------------------------------------------------------- | |
// ---------------------------------------------------------------------------------------------------------------------------------------- | |
// In the commented example below, we use the old javascript syntax to define the function getCoderSchoolStaff(). | |
// Although this works, we should prefer to use the new ES6 syntax. | |
// OLD Javascript | |
// function getCoderSchoolStaff(persons) { | |
// const coderSchoolStaff = [] | |
// persons.map(person => { | |
// if (person.company === 'CoderSchool' && person.occupation === 'Instructor') { | |
// coderSchoolStaff.push(person) | |
// } | |
// }) | |
// return coderSchoolStaff | |
// } | |
// New ES6 | |
// What can you see that's different with this definition and line 143? | |
// 1. | |
// Notice that the 'function' keyword is replaced by const. Also, there is a equal = between the function name and argument(s). | |
// 2. | |
// Notice also how the parentheses can be left out if the function takes exactly one argument(line 161 & 168 are exactly the same). | |
// const getCoderSchoolStaff = (persons) => { | |
// 3. | |
// Lastly, notice how the argument is proceeded by a fat arrow => and then the opening curly brace of the function body | |
// ---------------------------------------------------------------------------------------------------------------------------------------- | |
// ---------------------------------------------------------------------------------------------------------------------------------------- | |
const getCoderSchoolStaff = persons => { | |
const coderSchoolStaff = [] | |
persons.map(person => { | |
// SLOW DOWN LOOP | |
// RUN CODE IN CONSOLE AND SEE WHAT CONSOLE OUTPUTS ON EACH ITERATION OF THIS LOOP | |
// COMMENT OUT WHEN CONFIDENT WE UNDERSTAND HOW THIS POOL WILL BEHAVE ON EACH ITERATION | |
(() => setTimeout(() => { | |
console.log('%cElement in the "people" array: ', 'color: green', idx) | |
console.log(`%cPerson: `, 'color: green', person.firstName) | |
console.log(person) | |
}, 5000 * idx))(idx); | |
if (person.company === 'CoderSchool' && person.occupation === 'Instructor') { | |
coderSchoolStaff.push(person) | |
} | |
}) | |
return coderSchoolStaff | |
} | |
const coderSchoolStaff = getCoderSchoolStaff(people) | |
console.log('CoderSchoolStaff: ', coderSchoolStaff) | |
// 2. Define a function getMostPopularPerson() which takes the people array as an argument | |
// and returns an object. The object will have two keys. A person key will have an object as it's value. | |
// The total key will have the total of followers & friends of the most popular person. The person with the most followers & friends | |
// is the most popular. | |
// It should look like this { person: { firstName: 'Loi' }, total: 1000 } | |
const getMostPopularPerson = persons => { | |
const mostPopular = { person: {}, score : 0 } | |
persons.map((person, idx) => { | |
// SLOW DOWN LOOP | |
// RUN CODE IN CONSOLE AND SEE WHAT CONSOLE OUTPUTS ON EACH ITERATION OF THIS LOOP | |
// COMMENT OUT WHEN CONFIDENT WE UNDERSTAND HOW THIS POOL WILL BEHAVE ON EACH ITERATION | |
(() => setTimeout(() => { | |
console.log('%cElement in the "people" array: ', 'color: green', idx) | |
console.log(`%cPerson: `, 'color: green', person.firstName) | |
console.log(person) | |
}, 5000 * idx))(idx); | |
const popularityScore = person.friendsCount + person.followers | |
if (popularityScore > mostPopular.score) { | |
mostPopular.score = popularityScore | |
mostPopular.person = person | |
} | |
}) | |
return mostPopular | |
} | |
const mostPopularPerson = getMostPopularPerson(people) | |
console.log('MostPopularPerson: ', mostPopularPerson) | |
======= Nguyen | |
const getMostPopularPerson2 = (arr) => { | |
//map through array | |
//calculate the total of followers + friends | |
let newArray = [] | |
arr.map((el, index) => { | |
newArray[index] = { | |
person: { | |
firstName: el.firstName | |
}, | |
total: el.friendsCount + el.followers | |
} | |
}) | |
//with new array, find max Math.max() | |
return newArray.sort((a,b) => b.total - a.total)[0] | |
} | |
console.log(getMostPopularPerson2(people)) | |
// 3. Define a function getAmericans() which takes the people array as an argument | |
// and returns an array of people who are Americans. | |
// It should look like this[{ firstName: 'Loi', ...}, { firstName: 'Charles', ...}] | |
const getAmericans = persons => { | |
const americans = [] | |
persons.map((person, idx) => { | |
// SLOW DOWN LOOP | |
// RUN CODE IN CONSOLE AND SEE WHAT CONSOLE OUTPUTS ON EACH ITERATION OF THIS LOOP | |
// COMMENT OUT WHEN CONFIDENT WE UNDERSTAND HOW THIS POOL WILL BEHAVE ON EACH ITERATION | |
(() => setTimeout(() => { | |
console.log(`%cElement in people[${idx}]...`, 'color: green') | |
console.log(`%cObject...`, 'color: green', person) | |
}, 5000 * idx))(idx); | |
if (person.nationality === 'USA' || person.nationality === 'Murrican') { | |
americans.push(person) | |
} | |
}) | |
return americans | |
} | |
const americans = getAmericans(people) | |
console.log('Americans: ', americans) | |
============= | |
const getAmericans2 = (arr) => { | |
//filter | |
return arr.filter(el => { | |
return el.nationality === "USA" || el.nationality === "Murrican" | |
}) | |
//for loop. check if american => push to new array | |
//map, foreach. | |
} | |
console.log(getAmericans2(people)) | |
============ method 3 | |
const getAmericans3 = (arr) => { | |
const americans = [] | |
//for loop. check if american => push to new array | |
//map, foreach. | |
arr.forEach(el => { | |
if(el.nationality === "USA" || el.nationality === "Murrican"){ | |
americans.push(el) | |
} | |
}) | |
return americans | |
} | |
console.log(getAmericans3(people)) | |
// 4. Define a function findVietnamese() which will take the people array as an argument and | |
// return a single array. The array will contain all students who have nationality as Vietnamese. | |
// Make sure the function will account for 'VN' and 'vn' | |
// It should look like this [{}, {}, {}, ...] | |
const findVietnamese = (arr) => { | |
return arr.filter(el => { | |
return el.nationality.toUpperCase() == "VN" || el.nationality.toLowerCase() == "vietnamese" | |
}) | |
} | |
console.log(findVietnamese(people)) | |
// 5. Define a function findFavoriteColors() which will take the people array as an argument and | |
// return one array. The array will contain a list of UNIQUE colors collected from all persons. | |
// It should look like this ['red', 'black', 'pink', ...] | |
const findFavoriteColors = (arr) => { | |
//take out all the colors | |
const colors = arr.map(el => el.favoriteColor) | |
console.log(colors) | |
//get rid of duplicates | |
for(let i=0; i<colors.length; i++){ | |
for(let j=i+1; j<colors.length; j++){ | |
if(colors[i].toLowerCase()===colors[j].toLowerCase()){ | |
colors.splice(j,1) | |
} | |
} | |
} | |
return colors.map(el => el.toLowerCase()) | |
} | |
console.log(findFavoriteColors(people)) | |
// 6. Define a function findAdults() which will take the people array as an argument and | |
// return one array. The array will contain all students who's age is above 18 and above | |
// It should look like this [{}, {}, {}, ...] | |
const findAdults = (arr) => { | |
//filter people >=18 && students | |
return arr.filter(el => { | |
return el.age >= 18 && el.occupation !== "Instructor" //assuming only instructor vs students | |
}) | |
//or for loop | |
} | |
console.log(findAdults(people)) | |
======== 2 | |
const findAdults2 = (arr) => { | |
//or for loop | |
const adults = []; | |
arr.forEach(el => { | |
if(el.age >= 18 && el.occupation !== "Instructor"){ | |
adults.push(el) | |
} | |
}) | |
return adults | |
} | |
console.log(findAdults2(people)) | |
// 7. Define a function splitIntoMinorsAndAdults() which will take the people array as an argument and | |
// return three arrays. The first array will have two arrays within it. | |
// The two nested arrays will contain objects. | |
// It should look like this [[{}, {}, {}, ...], [{}, {}, {}, ...]] | |
const splitIntoMinorsAndAdults = (arr) => { | |
//get minors | |
const minors = arr.filter(el => el.age < 18) | |
//get adults | |
const adults = arr.filter(el => el.age >= 18) | |
//push into big array | |
return [minors, adults] | |
} | |
console.log(splitIntoMinorsAndAdults(people)) | |
// 8. Define a function findMostPopularColor() which will take the people array as an argument and | |
// return one string. The string will be the color which has the most people that have it as their favorite. | |
// In the event there are two colors with equal numbers. Return a string that says 'x and y were really popular!' | |
// It should look like this 'black' or 'black and red were really popular!' | |
const findMostPopularColor = (arr) => { | |
//find all the colors | |
const colors = arr.map(el => el.favoriteColor.toLowerCase()) | |
console.log(colors) | |
const count = {} | |
//for loop | |
colors.forEach(el => { | |
count[el] = count[el] ? count[el] + 1 : 1 | |
}) | |
// make an object, count | |
console.log(count) | |
const keys = Object.keys(count) | |
return `${keys.sort((a,b) => count[b] - count[a])[0]}` | |
//find max | |
} | |
console.log(findMostPopularColor(people)) | |
// 9. Define a function findNguyens() which will take the people array as an argument and | |
// return one array. The array will contain persons whose last names are Nguyen | |
// It should look like this [{}, {}] | |
const findNguyens = (arr) => { | |
//filter out the Nguyens | |
return arr.filter(el => el.lastName.toLowerCase() === "nguyen") | |
} | |
console.log(findNguyens(people)) | |
====== | |
const findNguyens2 = (arr) => { | |
//filter out the Nguyens | |
const nguyens = [] | |
arr.forEach(el => { | |
if(el.lastName.toLowerCase() === "nguyen"){ | |
nguyens.push(el) | |
} | |
}) | |
return nguyens | |
} | |
console.log(findNguyens2(people)) | |
// 10. Define a function sortOldToYoung() which will take the people array as an argument and | |
// return one array. The array will contain all students sorted in order from oldest to youngest | |
// It should look like this [{}, {}, {}, ...] | |
const sortOldToYoung = (arr) => { | |
//filter out students | |
//sort | |
return arr.filter(el => el.occupation !== "Instructor").sort((a,b) => b.age - a.age) | |
} | |
console.log(sortOldToYoung(people)) | |
// 11. Define a function findBirthYears() which will take the people array as an argument and | |
// return one array. The array will contain a list of all years which the people were born. | |
// It should look like this ['1997', '1990', '1987', ...] | |
const findBirthYears = (arr) => { | |
//find birth years | |
//remove duplicate | |
const years = arr.map(el => new Date().getFullYear() - el.age) | |
return [... new Set(years)] | |
} | |
console.log(findBirthYears(people)) | |
// 12. Define a function findOccupations() which will take the people array as an argument and | |
// return one array. The array will contain a list of UNIQUE occupations. | |
// It should look like this ['CEO', 'Instructor', 'Student'] | |
const findOccupations = (arr) => { | |
return [...new Set(arr.map(el => el.occupation))] | |
} | |
console.log(findOccupations(people)) | |
// 13. Define a function findEnrolledStudents() which will take the people array as an argument and | |
// return one array. The array will contain a list of people who have occupation listed as 'Student'. | |
// It should look like this [{}, {}, {}] | |
const findEnrolledStudents = (arr) => { | |
return arr.filter(el => el.occupation.toLowerCase() === "student" || el.occupation.toLowerCase() === "code learner") | |
} | |
console.log(findEnrolledStudents(people)) | |
// 14. Define a function addBirthPlacesToUsers() which will take the people array as an argument and | |
// return one array. The array will contain all the original objects in the array with an additional | |
// property(birthPlace) with the value of a new object {} attacheed to each object. | |
// It should look like this [{firstName: 'Loi', birthPlace: {}, ...}] | |
const addBirthPlacesToUsers = (arr) => { | |
//map. add new property | |
arr.map(el => { | |
return el['birthPlace'] = {}}) | |
return arr | |
} | |
console.log(addBirthPlacesToUsers(people)) | |
// 15. Define a function addGenderToPeople() which will take the people array as an argument and | |
// return one array. The array will contain all the original objects in the array with an additional | |
// property(gender) with the value of an empty string '' attacheed to each object. | |
// It should look like this [{firstName: 'Loi', gender: '', ...}] | |
const addGenderToPeople = (arr) => { | |
//map add gender '' | |
arr.map(el => el['gender'] = '') | |
return arr | |
} | |
console.log(addGenderToPeople(people)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment