Create a function 'calcAverageHumanAge', which accepts an arrays of dog's ages ('ages'), and does the following things in order:
Test data:
Data 1: [5, 2, 4, 1, 15, 8, 3] Data 2: [16, 6, 10, 5, 6, 1, 4]
My solution(idk why wont work):
const calcAverageHumanAge = function (ageList) {
const avgAge = ageList
.map(val => (val <= 2 ? 2 * val : 16 + val * 4))
.fliter(val => val >= 18)
.reduce((acc, val, i, list) => {
return acc + val / list.length;
}, 0);};
You have three issues. Your reduce doesn't return anything is the main problem, but you're also dividing by list.length in each callback which doesn't make any sense (actually it does and I'm dumb), and then you aren't returning anything from the function. You want something like this:
const calcAverageHumanAge = function (ageList) {
const filteredVals = ageList
.map(val => (val <= 2 ? 2 * val : 16 + val * 4))
.filter(val => val >= 18);
return filteredVals.reduce((acc, val) => acc + val) / filteredVals.length;
};
When run on your data:
calcAverageHumanAge([5, 2, 4, 1, 15, 8, 3]); // 44
calcAverageHumanAge([16, 6, 10, 5, 6, 1, 4]); // 47.333