|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Array Cardio 💪💪</title> |
| 6 | +</head> |
| 7 | +<body> |
| 8 | + <p><em>Psst: have a look at the JavaScript Console</em> 💁</p> |
| 9 | + <script> |
| 10 | + // ## Array Cardio Day 2 |
| 11 | + |
| 12 | + const people = [ |
| 13 | + { name: 'Wes', year: 1988 }, |
| 14 | + { name: 'Kait', year: 1986 }, |
| 15 | + { name: 'Irv', year: 1970 }, |
| 16 | + { name: 'Lux', year: 2015 } |
| 17 | + ]; |
| 18 | + |
| 19 | + const comments = [ |
| 20 | + { text: 'Love this!', id: 523423 }, |
| 21 | + { text: 'Super good', id: 823423 }, |
| 22 | + { text: 'You are the best', id: 2039842 }, |
| 23 | + { text: 'Ramen is my fav food ever', id: 123523 }, |
| 24 | + { text: 'Nice Nice Nice!', id: 542328 } |
| 25 | + ]; |
| 26 | + |
| 27 | + // Some and Every Checks |
| 28 | + // Array.prototype.some() // is at least one person 19? |
| 29 | + |
| 30 | + // const isAdult = people.some(function(person) { |
| 31 | + // const currentYear = (new Date()).getFullYear(); |
| 32 | + // if(currentYear - person.year >= 19) { |
| 33 | + // return true; |
| 34 | + // } |
| 35 | + // }); |
| 36 | + const isAdult = people.some(person => ((new Date().getFullYear()) - person.year >= 19)); |
| 37 | + console.log({isAdult}); |
| 38 | + |
| 39 | + // Array.prototype.every() // is everyone 19? |
| 40 | + const isAdults = people.every(person => ((new Date().getFullYear()) - person.year >= 19)); |
| 41 | + console.log({isAdults}); |
| 42 | + |
| 43 | + |
| 44 | + // Array.prototype.find() |
| 45 | + // Find is like filter, but instead returns just the one you are looking for |
| 46 | + // find the comment with the ID of 823423 |
| 47 | + const comment = comments.find(comment => comment.id === 823423); |
| 48 | + console.log(comment); |
| 49 | + |
| 50 | + // Array.prototype.findIndex() |
| 51 | + // Find the comment with this ID of 823423 |
| 52 | + const commentIndex = comments.findIndex(comment => comment.id === 823423); |
| 53 | + console.log(commentIndex); |
| 54 | + |
| 55 | + // delete the comment with the ID of 823423 |
| 56 | + |
| 57 | + // way #1, using splice |
| 58 | + // comments.splice(commentIndex, 1); |
| 59 | + |
| 60 | + //way #2, copy original array until the commentIndex, then copy one past the |
| 61 | + //commentIndex and copy the rest. A new array is built! |
| 62 | + // es6 spread operator is needed (...) |
| 63 | + const newComments = [ |
| 64 | + ...comments.slice(0, commentIndex), |
| 65 | + ...comments.slice(commentIndex + 1) |
| 66 | + ]; |
| 67 | + |
| 68 | + |
| 69 | + </script> |
| 70 | +</body> |
| 71 | +</html> |
0 commit comments