|
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 fifteen = inventors.filter(function (item) { |
| 37 | + if(item.year >= 1500 && item.year <= 1599) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + }); |
| 41 | + console.table(fifteen); |
36 | 42 |
|
37 | 43 | // Array.prototype.map()
|
38 | 44 | // 2. Give us an array of the inventors' first and last names
|
| 45 | + const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`); |
| 46 | + console.log(fullNames); |
39 | 47 |
|
40 | 48 | // Array.prototype.sort()
|
41 | 49 | // 3. Sort the inventors by birthdate, oldest to youngest
|
| 50 | + const ordered = inventors.sort((a, b) => (a.year > b.year) ? 1 : -1); |
| 51 | + console.table(ordered); |
42 | 52 |
|
43 | 53 | // Array.prototype.reduce()
|
44 | 54 | // 4. How many years did all the inventors live?
|
| 55 | + const totalYears = inventors.reduce((total, inventor) => { |
| 56 | + return total + (inventor.passed - inventor.year); |
| 57 | + }, 0); |
| 58 | + console.log(totalYears); |
45 | 59 |
|
46 | 60 | // 5. Sort the inventors by years lived
|
| 61 | + const sorted = inventors.sort(function(a, b) { |
| 62 | + const years = (inventor) => inventor.passed - inventor.year; |
| 63 | + return (years(a) > years(b)) ? -1 : 1; |
| 64 | + }); |
| 65 | + console.table(sorted); |
47 | 66 |
|
48 | 67 | // 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
|
49 | 68 | // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
|
50 | 69 |
|
| 70 | + // const category = document.querySelector('.mw-category'); |
| 71 | + // const links = Array.from(category.querySelectorAll('a')); // because there is NodeList |
| 72 | + // const de = links |
| 73 | + // .map(link => link.textContent) |
| 74 | + // .filter(streetName => streetName.includes('de')); |
51 | 75 |
|
52 | 76 | // 7. sort Exercise
|
53 | 77 | // Sort the people alphabetically by last name
|
| 78 | + const alpha = people.sort((a, b) => { |
| 79 | + const [aLast, aFirst] = a.split(', '); |
| 80 | + const [bLast, bFirst] = b.split(', '); |
| 81 | + return aLast > bLast ? 1 : -1; |
| 82 | + }); |
| 83 | + console.log(alpha); |
54 | 84 |
|
55 | 85 | // 8. Reduce Exercise
|
56 | 86 | // Sum up the instances of each of these
|
57 | 87 | const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
|
58 | 88 |
|
| 89 | + const transport = data.reduce(function(obj, item) { |
| 90 | + if(!obj[item]) { |
| 91 | + obj[item] = 0; |
| 92 | + } |
| 93 | + obj[item]++; |
| 94 | + return obj; |
| 95 | + }, {}); |
| 96 | + console.log(transport); |
| 97 | + |
59 | 98 | </script>
|
60 | 99 | </body>
|
61 | 100 | </html>
|
0 commit comments