Last active
June 16, 2023 18:11
-
-
Save kironroy/99f3b5f8be653539fa7b0634e931b2c2 to your computer and use it in GitHub Desktop.
map, filter, reduce in action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const agesOneArr = [5, 2, 4, 1, 15, 8, 3]; | |
const agesTwoArr = [16, 6, 10, 5, 6, 1, 4]; | |
const calcAverageHumanAge = function (ages) { | |
const dogToHumanYrs = ages.map((age, i) => | |
age <= 2 ? 2 * age : 16 + age * 4 | |
); | |
const eighteenOrOlder = dogToHumanYrs.filter(age => age > 18); | |
console.log(eighteenOrOlder); | |
const averageAge = eighteenOrOlder.reduce( | |
(a, b) => a + b / eighteenOrOlder.length, | |
0 | |
); | |
return averageAge; | |
}; | |
// method chaining | |
console.log(calcAverageHumanAge(agesOneArr)); | |
console.log(calcAverageHumanAge(agesTwoArr)); | |
console.log(`----------------------`); | |
const calcAverageHumanAgeSlim = function (ages) { | |
const dogToHumanYrs = ages | |
.map((age, i) => (age <= 2 ? 2 * age : 16 + age * 4)) | |
.filter(age => age > 18) | |
.reduce((acc, age, i, arr) => acc + age / arr.length, 0); | |
return dogToHumanYrs; | |
}; | |
console.log(calcAverageHumanAgeSlim(agesOneArr)); | |
console.log(calcAverageHumanAgeSlim(agesTwoArr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment