|
33 | 33 |
|
34 | 34 | // Array.prototype.filter() |
35 | 35 | // 1. Filter the list of inventors for those who were born in the 1500's |
| 36 | + const inventorsFromThe1500s = inventors.filter(inventor => inventor.year >= 1500 && inventor.year <= 1599) |
| 37 | + console.table(inventorsFromThe1500s); |
36 | 38 |
|
37 | 39 | // Array.prototype.map() |
38 | 40 | // 2. Give us an array of the inventors' first and last names |
| 41 | + const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`) |
| 42 | + console.table(fullNames); |
39 | 43 |
|
40 | 44 | // Array.prototype.sort() |
41 | 45 | // 3. Sort the inventors by birthdate, oldest to youngest |
| 46 | + const sorted = [].concat(inventors).sort((a, b) => b.year - a.year); |
| 47 | + console.table(sorted); |
42 | 48 |
|
43 | 49 | // Array.prototype.reduce() |
44 | 50 | // 4. How many years did all the inventors live? |
| 51 | + const totalYearsOfScience = inventors.reduce((sum, inventor) => sum + lived(inventor), 0) |
| 52 | + console.log(totalYearsOfScience); |
45 | 53 |
|
46 | 54 | // 5. Sort the inventors by years lived |
| 55 | + const oldest = [].concat(inventors).sort((a, b) => lived(b) - lived(a)); |
| 56 | + console.table(oldest); |
47 | 57 |
|
48 | 58 | // 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name |
49 | 59 | // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris |
50 | | - |
| 60 | + const boulevardsWithDe = Array.prototype.map.call( |
| 61 | + document.querySelectorAll('.mw-category li a'), |
| 62 | + anchor => anchor.textContent |
| 63 | + ).filter(boulevard => boulevard.indexOf('de') !== -1); |
51 | 64 |
|
52 | 65 | // 7. sort Exercise |
53 | 66 | // Sort the people alphabetically by last name |
| 67 | + const alphabeticallyOrdered = [].concat(people).sort((a, b) => lastName(a) > lastName(b) ? 1 : -1); |
| 68 | + console.log(alphabeticallyOrdered); |
54 | 69 |
|
55 | 70 | // 8. Reduce Exercise |
56 | 71 | // Sum up the instances of each of these |
57 | 72 | const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ]; |
| 73 | + const countsOfVehicles = data.reduce( |
| 74 | + (hash, vehicle) => { |
| 75 | + hash[vehicle] = (hash[vehicle] || 0) + 1; |
| 76 | + return hash; |
| 77 | + }, |
| 78 | + {} |
| 79 | + ); |
| 80 | + console.log(countsOfVehicles); |
| 81 | + |
| 82 | + function lived(inventor) { |
| 83 | + return inventor.passed - inventor.year; |
| 84 | + } |
58 | 85 |
|
| 86 | + function lastName(fullName) { |
| 87 | + const [_, last] = fullName.split(', '); |
| 88 | + return last; |
| 89 | + } |
59 | 90 | </script> |
60 | 91 | </body> |
61 | 92 | </html> |
0 commit comments