I'm going through the book Eloquent Javascript, and I'm doing an exercise where I'm having trouble understand what I'm doing wrong. Here is code that computes the averages correctly(ancestry is a JSON object):
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
};
function age(p) { return p.died - p.born; };
function groupBy(array, action){
var groups = {};
array.forEach(function(individual){
var group = action(individual);
if (groups[group] == undefined)
groups[group] = [];
groups[group].push(individual);
});
return groups;
};
var centuries = groupBy(ancestry, function(person){
return Math.ceil(person.died / 100);
});
console.log(average(centuries[16].map(age)));
console.log(average(centuries[17].map(age)));
console.log(average(centuries[18].map(age)));
console.log(average(centuries[19].map(age)));
console.log(average(centuries[20].map(age)));
console.log(average(centuries[21].map(age)));
// → 16: 43.5
// 17: 51.2
// 18: 52.8
// 19: 54.8
// 20: 84.7
// 21: 94
Which is all fine and well. However, for the life of me I could not figure out how to write code that would not require the multiple console.log calls at the end. Here is the closest I could seem to come up with, but I kept getting a typeError and I don't understand why.
for (century in centuries) {
console.log(average(century.map(age)));
};
Why doesn't this for in loop work? Thanks in advance!
centuries["century"]