|
31 | 31 |
|
32 | 32 | // Array.prototype.filter()
|
33 | 33 | // 1. Filter the list of inventors for those who were born in the 1500's
|
| 34 | + const filteredInventors = inventors.filter(inventor => inventor.year < 1600 && inventor.year >= 1500 ) |
| 35 | + |
34 | 36 |
|
35 | 37 | // Array.prototype.map()
|
36 | 38 | // 2. Give us an array of the inventors' first and last names
|
| 39 | + const names = inventors.map(inventor => { |
| 40 | + return `${inventor.first} ${inventor.last}` |
| 41 | + }) |
37 | 42 |
|
38 | 43 | // Array.prototype.sort()
|
39 | 44 | // 3. Sort the inventors by birthdate, oldest to youngest
|
| 45 | + const sortByBirth = inventors.sort((x,y) => { |
| 46 | + const ageX = x.passed - x.year |
| 47 | + const ageY = y.passed - y.year |
| 48 | + return ageX < ageY ? 1 : -1 |
| 49 | + |
| 50 | + }) |
| 51 | + |
40 | 52 |
|
41 | 53 | // Array.prototype.reduce()
|
42 | 54 | // 4. How many years did all the inventors live?
|
| 55 | + const totalAge = inventors.reduce((total, inventor) => { |
| 56 | + const age = inventor.passed - inventor.year |
| 57 | + return total + age |
| 58 | + }, 0) |
43 | 59 |
|
44 | 60 | // 5. Sort the inventors by years lived
|
45 | 61 |
|
|
49 | 65 |
|
50 | 66 | // 7. sort Exercise
|
51 | 67 | // Sort the people alphabetically by last name
|
| 68 | + const sortPeople = people.sort(function(firstOne, lastOne){ |
| 69 | + const [aFirst, aLast] = firstOne.split(','); |
| 70 | + const [bFirst, bLast] = lastOne.split(','); |
| 71 | + return aLast > bLast ? 1 : -1 |
| 72 | + }) |
| 73 | + |
| 74 | + console.log(sortPeople) |
| 75 | + |
| 76 | + |
52 | 77 |
|
53 | 78 | // 8. Reduce Exercise
|
54 | 79 | // Sum up the instances of each of these
|
55 | 80 | const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
|
56 | 81 |
|
| 82 | + const sum = data.reduce((total, single) => { |
| 83 | + if(!total[single]){ |
| 84 | + total[single] = 1 |
| 85 | + }else{ |
| 86 | + total[single] += 1 |
| 87 | + } |
| 88 | + return total |
| 89 | + }, {}) |
| 90 | + |
| 91 | + |
| 92 | + |
57 | 93 | </script>
|
58 | 94 | </body>
|
59 | 95 | </html>
|
0 commit comments