|
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 |
| - |
| 34 | + let result_1 = inventors.filter((person) => person.year >= 1500 && person.year < 1600) |
| 35 | + console.table(result_1); |
| 36 | + |
35 | 37 | // Array.prototype.map()
|
36 | 38 | // 2. Give us an array of the inventors' first and last names
|
| 39 | + let result_2 = []; |
| 40 | + inventors.map(person => {result_2.push(person.first + ' ' + person.last)}) |
| 41 | + console.log(result_2); |
37 | 42 |
|
38 | 43 | // Array.prototype.sort()
|
39 | 44 | // 3. Sort the inventors by birthdate, oldest to youngest
|
| 45 | + inventors.sort((a, b) => (- a.year + b.year)) |
| 46 | + console.table(inventors); |
| 47 | + |
40 | 48 |
|
41 | 49 | // Array.prototype.reduce()
|
42 | 50 | // 4. How many years did all the inventors live?
|
| 51 | + // let total = 0; |
| 52 | + // inventors.reduce((prePerson, curPerson, curIdx, src) => { |
| 53 | + // total += (curPerson.passed - curPerson.year) |
| 54 | + // }, 0) |
| 55 | + // console.log(total); |
| 56 | + const totalYears = inventors.reduce((total, inventor) => (total + (inventor.passed - inventor.year)), 0); |
| 57 | + |
| 58 | + console.log(totalYears); |
43 | 59 |
|
44 | 60 | // 5. Sort the inventors by years lived
|
| 61 | + inventors.sort((a, b) => (-(a.passed - a.year) + (b.passed - b.year))) |
| 62 | + console.table(inventors); |
45 | 63 |
|
46 | 64 | // 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
|
47 | 65 | // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
|
48 | 66 |
|
| 67 | + /* run the code in console of the wiki page*/ |
| 68 | + // var result_6 = [...document.querySelectorAll('.mw-category a')].map(function(i){return i.innerHTML}); |
| 69 | + // result_6.filter((n) => n.indexOf('de')>=0); |
49 | 70 |
|
50 | 71 | // 7. sort Exercise
|
51 | 72 | // Sort the people alphabetically by last name
|
| 73 | + people.sort((a,b) => (a.split(',')[0].trim() > b.split(',')[0].trim() ? 1 : -1)); |
| 74 | + console.log(people) |
52 | 75 |
|
53 | 76 | // 8. Reduce Exercise
|
54 | 77 | // Sum up the instances of each of these
|
55 | 78 | const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
|
56 |
| - |
| 79 | + var result_8 = data.reduce((obj, item) => { |
| 80 | + if(obj.hasOwnProperty(item)) { |
| 81 | + obj[item] ++; |
| 82 | + } |
| 83 | + else { |
| 84 | + obj[item] = 0; |
| 85 | + } |
| 86 | + return obj; |
| 87 | + }, {}); |
| 88 | + console.log(result_8); |
| 89 | + |
57 | 90 | </script>
|
58 | 91 | </body>
|
59 | 92 | </html>
|
0 commit comments