Skip to content

Instantly share code, notes, and snippets.

@kironroy
Last active June 16, 2023 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kironroy/99f3b5f8be653539fa7b0634e931b2c2 to your computer and use it in GitHub Desktop.
Save kironroy/99f3b5f8be653539fa7b0634e931b2c2 to your computer and use it in GitHub Desktop.
map, filter, reduce in action
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