Exercise 27 - Averaging

At the end of exercise 27, Zed suggests “playing around” with chaining to (among other things), average the pet ages. I have been trying to do this, but have not yet cracked it. I tried writing a little “divide” function, and chaining it:

const divide = (num, arr) => {
return num / arr.length
}

let totalAges = pets.map(pet => pet.age)
.reduce((acc, age) => acc += age)
.divide(totalAges, pets)

But I get the following error:

ReferenceError: totalAges is not defined

I intuitively knew this was off somehow, but for the life of me I cannot figure this out. Any ideas?

I guess I sort of rubber ducked this one by doing this:

const divide = (num, arr) => {
return num / arr.length
}

let avAges = pets.map(pet => pet.age)
.reduce((acc, age) => acc += age) / pets.length;

console.log(avAges)

However, I still feel like this wasn;t exactly what Zed has in mind? Zed? Any feedback on this? Thanks!

Close…so you only have .map, .reduce, .filter, .search, and .forEach right? You can’t really just add your own .divide. That’s the first thing.

Next, you can call .reduce to produce a single number. You basically did that and then did / pets.length to get the average. So, you don’t need the divide() function anymore. That’s the end. There’s another more complicated way to do it where you don’t need to do a complete sum of the whole list, but instead can do it incrementally, but that’s some more involved math.