|
| 1 | +// ## Array Cardio Day 2 |
| 2 | + |
| 3 | + const people = [ |
| 4 | + { name: 'Wes', year: 1988 }, |
| 5 | + { name: 'Kait', year: 1986 }, |
| 6 | + { name: 'Irv', year: 1970 }, |
| 7 | + { name: 'Lux', year: 2015 } |
| 8 | + ]; |
| 9 | + |
| 10 | + const comments = [ |
| 11 | + { text: 'Love this!', id: 523423 }, |
| 12 | + { text: 'Super good', id: 823423 }, |
| 13 | + { text: 'You are the best', id: 2039842 }, |
| 14 | + { text: 'Ramen is my fav food ever', id: 123523 }, |
| 15 | + { text: 'Nice Nice Nice!', id: 542328 } |
| 16 | + ]; |
| 17 | + |
| 18 | + // Some and Every Checks |
| 19 | + // Array.prototype.some() // is at least one person 19 or older? |
| 20 | + |
| 21 | + // 抓到今年 |
| 22 | + const currentYear = (new Date()).getFullYear(); |
| 23 | + |
| 24 | + // 回傳每一個人的年紀 |
| 25 | + const personYear = people.map(person => currentYear - person.year); |
| 26 | + console.table(personYear); |
| 27 | + |
| 28 | + const isAdult = people.some(person => (currentYear - person.year >= 19)); |
| 29 | + console.log(isAdult); |
| 30 | + |
| 31 | + |
| 32 | + // Array.prototype.every() // is everyone 19 or older? |
| 33 | + |
| 34 | + const isAllAdult = people.every(person => (currentYear - person.year >= 19)) |
| 35 | + console.log(isAllAdult); |
| 36 | + |
| 37 | + |
| 38 | + // Array.prototype.find() |
| 39 | + // Find is like filter, but instead returns just the one you are looking for |
| 40 | + // find the comment with the ID of 823423 |
| 41 | + |
| 42 | + const findComment = comments.find(comment => (comment.id === 823423)).text |
| 43 | + console.log(findComment); |
| 44 | + |
| 45 | + // Array.prototype.findIndex() |
| 46 | + // Find the comment with this ID |
| 47 | + // delete the comment with the ID of 123523 |
| 48 | + |
| 49 | + // 找到 123523 的 Index |
| 50 | + const findIndexComment = comments.findIndex(comment => (comment.id === 123523)) |
| 51 | + console.log(findIndexComment); |
| 52 | + |
| 53 | + // 刪除原陣列資料 splice |
| 54 | + // comments.splice(findIndexComment,1); |
| 55 | + // console.table(comments); |
| 56 | + |
| 57 | + // 刪掉資料並產生新的陣列 |
| 58 | + const newComments = [ |
| 59 | + ...comments.slice(0,findIndexComment), // 複製起始 index(0) 到 findIndexComment (不包含自己) |
| 60 | + ...comments.slice(findIndexComment+1) // 複製 findIndexComment+1 到之後的資料 |
| 61 | + ] |
| 62 | + console.table(newComments); |
0 commit comments