Created
May 1, 2019 15:59
-
-
Save Mawulijo/a48ad0ce21e2b5a4c26bb91631b8ca81 to your computer and use it in GitHub Desktop.
Solutions to foEach challenge
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
const users = [ | |
{ id: 1, name: 'luke', age: 67, bestFriend: 'R2', pay: '', isOldest: undefined}, | |
{ id: 2, name: 'han', age: 76, bestFriend: 'Chewie', pay: '', isOldest: undefined}, | |
{ id: 3, name: 'chewie', age: 74, bestFriend: 'Han', pay: '', isOldest: undefined}, | |
{ id: 4, name: 'rey', age: 26, bestFriend: 'Finn', pay: '', isOldest: undefined}, | |
{ id: 5, name: 'kylo', age: 35, bestFriend: 'Kylo', pay: '', isOldest: undefined}, | |
] | |
// ====================1================== | |
// FOR LOOP 1 | |
// pay them | |
// for(let i=0; i < users.length; i++) { | |
// users[i].pay = 'SO MUCH MOOLAH' | |
// } | |
users.forEach((user) => { | |
user.pay = 'SO MUCH MOOLAH'; | |
}); | |
// ====================2================== | |
// FOR LOOP 2 | |
// calculate birth year | |
// for(let i=0; i < users.length; i++) { | |
// users[i].birthyear = 2019 - users[i].age | |
// } | |
users.forEach((user)=>{user.birthyear = 2019 - user.age}); | |
// ====================3================== | |
// FOR LOOP 3 | |
// capitalize first letter of name | |
// for(let i=0; i < users.length; i++) { | |
// users[i].name = users[i].name[0].toLocaleUpperCase() + users[i].name.slice(1) | |
// } | |
users.forEach((user)=>{ | |
user.name = user.name[0].toUpperCase()+user.name.slice(1) | |
}); | |
// ===================4=================== | |
// FOR LOOP 4 | |
// mark the oldest | |
// var idxOfOldest = users[0]; | |
// for(let i=0; i < users.length; i++) { | |
// if(users[i].age > users[idxOfOldest].age) | |
// idxOfOldest = i; | |
// } | |
// users[idxOfOldest].isOldest = true; | |
var idxOfOldest = users[0]; | |
users.forEach((user)=>{ | |
if(idxOfOldest.age < user.age) | |
idxOfOldest = user; | |
}); | |
idxOfOldest.isOldest = true; | |
// ===================5=================== | |
// let html = ""; | |
// FOR LOOP 5 | |
// for(let i=0; i < users.length; i++) { | |
// html += "<div>"+ (i+1) + '. ' + users[i].name + ', ' + users[i].age + 'yrs old'; | |
// if(users[i].isOldest) | |
// html += ' OLDEST' | |
// html += '</div>'; | |
// } | |
let html = ""; | |
users.forEach((user)=>{ | |
html += "<div>"+ (user.id+0) + '. ' + user.name + ', ' + user.age + 'yrs old,' + ' Best friend is '+user.bestFriend; | |
if (user.isOldest) | |
html += ' OLDEST' | |
html += '</div>'; | |
}); | |
const appDiv = document.getElementById('app'); | |
appDiv.innerHTML = html; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment