Udemy. 11. Arrays
challenge #2 & #3
by trentHarlem
HTML
<h1>
///////////////////////////////////////<br>
// Coding Challenge #2
</h1>
<p>
Let's go back to Julia and Kate's study about dogs. This time, they want to convert dog ages to human ages and calculate the average age of the dogs in their study.
<br><br>
Create a function 'calcAverageHumanAge', which accepts an arrays of dog's ages ('ages'), and does the following things in order:<br><br>
1. Calculate the dog age in human years using the following formula: if the dog is <= 2 years old, humanAge = 2 * dogAge. If the dog is > 2 years old, humanAge = 16 + dogAge * 4.<br><br>
2. Exclude all dogs that are less than 18 human years old (which is the same as keeping dogs that are at least 18 years old)<br><br>
3. Calculate the average human age of all adult dogs (you should already know from other challenges how we calculate averages π)<br><br>
4. Run the function for both test datasets<br>
TEST DATA 1: [5, 2, 4, 1, 15, 8, 3]<br>
TEST DATA 2: [16, 6, 10, 5, 6, 1, 4]<br>
GOOD LUCK π
</p>
<h2>
Challenge #3
</h2>
<P>
complete this challenge with an arrow function and method chaining
</P>
CSS
body {
font: 1.1em system-ui;
}
JavaScript
const calcAverageHumanAge = ages =>
ages
.map(dogAge => dogAge <= 2 ? 2 * dogAge : 16 + dogAge * 4)
.filter(humanAge => humanAge >= 18)
.reduce((a, c, i, arr) =>
a + c / arr.length, 0)
// i already completed chall #3 without realizing it π
console.log(
//TEST DATA 1:
calcAverageHumanAge([5, 2, 4, 1, 15, 8, 3]),
//TEST DATA 2:
calcAverageHumanAge([16, 6, 10, 5, 6, 1, 4])
)